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;
/**
* @dev winner events
*/
contract WinnerEvents {
event onBuy
(
address paddr,
uint256 ethIn,
string reff,
uint256 timeStamp
);
event onBuyUseBalance
(
address paddr,
uint256 keys,
uint256 timeStamp
);
event onBuyName
(
address paddr,
bytes32 pname,
uint256 ethIn,
uint256 timeStamp
);
event onWithdraw
(
address paddr,
uint256 ethOut,
uint256 timeStamp
);
event onUpRoundID
(
uint256 roundID
);
event onUpPlayer
(
address addr,
bytes32 pname,
uint256 balance,
uint256 interest,
uint256 win,
uint256 reff
);
event onAddPlayerOrder
(
address addr,
uint256 keys,
uint256 eth,
uint256 otype
);
event onUpPlayerRound
(
address addr,
uint256 roundID,
uint256 eth,
uint256 keys,
uint256 interest,
uint256 win,
uint256 reff
);
event onUpRound
(
uint256 roundID,
address leader,
uint256 start,
uint256 end,
bool ended,
uint256 keys,
uint256 eth,
uint256 pool,
uint256 interest,
uint256 win,
uint256 reff
);
}
/*
* @dev winner contract
*/
contract Winner is WinnerEvents {
using SafeMath for *;
using NameFilter for string;
//==============================================================================
// game settings
//==============================================================================
string constant public name = "Im Winner Game";
string constant public symbol = "IMW";
//==============================================================================
// public state variables
//==============================================================================
// activated flag
bool public activated_ = false;
// round id
uint256 public roundID_;
// *************
// player data
// *************
uint256 private pIDCount_;
// return pid by address
mapping(address => uint256) public address2PID_;
// return player data by pid (pid => player)
mapping(uint256 => WinnerDatasets.Player) public pID2Player_;
// return player round data (pid => rid => player round data)
mapping(uint256 => mapping(uint256 => WinnerDatasets.PlayerRound)) public pID2Round_;
// return player order data (pid => rid => player order data)
mapping(uint256 => mapping(uint256 => WinnerDatasets.PlayerOrder[])) public pID2Order_;
// *************
// round data
// *************
// return the round data by rid (rid => round)
mapping(uint256 => WinnerDatasets.Round) public rID2Round_;
constructor()
public
{
pIDCount_ = 0;
}
//==============================================================================
// function modifiers
//==============================================================================
/*
* @dev check if the contract is activated
*/
modifier isActivated() {
require(activated_ == true, "the contract is not ready yet");
_;
}
/**
* @dev check if the msg sender is human account
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/*
* @dev check if admin or not
*/
modifier isAdmin() {
require( msg.sender == 0x74B25afBbd16Ef94d6a32c311d5c184a736850D3, "sorry admins only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 10000000000, "eth too small");
require(_eth <= 100000000000000000000000, "eth too huge");
_;
}
//==============================================================================
// public functions
//==============================================================================
/*
* @dev send eth to contract
*/
function ()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable {
buyCore(msg.sender, msg.value, "");
}
/*
* @dev send eth to contract
*/
function buyKey()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable {
buyCore(msg.sender, msg.value, "");
}
/*
* @dev send eth to contract
*/
function buyKeyWithReff(string reff)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable {
buyCore(msg.sender, msg.value, reff);
}
/*
* @dev buy key use balance
*/
function buyKeyUseBalance(uint256 keys)
isActivated()
isHuman()
public {
uint256 pID = address2PID_[msg.sender];
require(pID > 0, "cannot find player");
// fire buy event
emit WinnerEvents.onBuyUseBalance
(
msg.sender,
keys,
now
);
}
/*
* @dev buy name
*/
function buyName(string pname)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable {
uint256 pID = address2PID_[msg.sender];
// new player
if( pID == 0 ) {
pIDCount_++;
pID = pIDCount_;
WinnerDatasets.Player memory player = WinnerDatasets.Player(pID, msg.sender, 0, 0, 0, 0, 0);
WinnerDatasets.PlayerRound memory playerRound = WinnerDatasets.PlayerRound(0, 0, 0, 0, 0);
pID2Player_[pID] = player;
pID2Round_[pID][roundID_] = playerRound;
address2PID_[msg.sender] = pID;
}
pID2Player_[pID].pname = pname.nameFilter();
// fire buy event
emit WinnerEvents.onBuyName
(
msg.sender,
pID2Player_[pID].pname,
msg.value,
now
);
}
//==============================================================================
// private functions
//==============================================================================
function buyCore(address addr, uint256 eth, string reff)
private {
uint256 pID = address2PID_[addr];
// new player
if( pID == 0 ) {
pIDCount_++;
pID = pIDCount_;
WinnerDatasets.Player memory player = WinnerDatasets.Player(pID, addr, 0, 0, 0, 0, 0);
WinnerDatasets.PlayerRound memory playerRound = WinnerDatasets.PlayerRound(0, 0, 0, 0, 0);
pID2Player_[pID] = player;
pID2Round_[pID][roundID_] = playerRound;
address2PID_[addr] = pID;
}
// fire buy event
emit WinnerEvents.onBuy
(
addr,
eth,
reff,
now
);
}
//==============================================================================
// admin functions
//==============================================================================
/*
* @dev activate the contract
*/
function activate()
isAdmin()
public {
require( activated_ == false, "contract is activated");
activated_ = true;
// start the first round
roundID_ = 1;
}
/**
* @dev inactivate the contract
*/
function inactivate()
isAdmin()
isActivated()
public {
activated_ = false;
}
/*
* @dev user withdraw
*/
function withdraw(address addr, uint256 eth)
isActivated()
isAdmin()
isWithinLimits(eth)
public {
uint pID = address2PID_[addr];
require(pID > 0, "user not exist");
addr.transfer(eth);
// fire the withdraw event
emit WinnerEvents.onWithdraw
(
msg.sender,
eth,
now
);
}
/*
* @dev update round id
*/
function upRoundID(uint256 roundID)
isAdmin()
isActivated()
public {
require(roundID_ != roundID, "same to the current roundID");
roundID_ = roundID;
// fire the withdraw event
emit WinnerEvents.onUpRoundID
(
roundID
);
}
/*
* @dev upPlayer
*/
function upPlayer(address addr, bytes32 pname, uint256 balance, uint256 interest, uint256 win, uint256 reff)
isAdmin()
isActivated()
public {
uint256 pID = address2PID_[addr];
require( pID != 0, "cannot find the player");
require( balance >= 0, "balance invalid");
require( interest >= 0, "interest invalid");
require( win >= 0, "win invalid");
require( reff >= 0, "reff invalid");
pID2Player_[pID].pname = pname;
pID2Player_[pID].balance = balance;
pID2Player_[pID].interest = interest;
pID2Player_[pID].win = win;
pID2Player_[pID].reff = reff;
// fire the event
emit WinnerEvents.onUpPlayer
(
addr,
pname,
balance,
interest,
win,
reff
);
}
function upPlayerRound(address addr, uint256 roundID, uint256 eth, uint256 keys, uint256 interest, uint256 win, uint256 reff)
isAdmin()
isActivated()
public {
uint256 pID = address2PID_[addr];
require( pID != 0, "cannot find the player");
require( roundID == roundID_, "not current round");
require( eth >= 0, "eth invalid");
require( keys >= 0, "keys invalid");
require( interest >= 0, "interest invalid");
require( win >= 0, "win invalid");
require( reff >= 0, "reff invalid");
pID2Round_[pID][roundID_].eth = eth;
pID2Round_[pID][roundID_].keys = keys;
pID2Round_[pID][roundID_].interest = interest;
pID2Round_[pID][roundID_].win = win;
pID2Round_[pID][roundID_].reff = reff;
// fire the event
emit WinnerEvents.onUpPlayerRound
(
addr,
roundID,
eth,
keys,
interest,
win,
reff
);
}
/*
* @dev add player order
*/
function addPlayerOrder(address addr, uint256 roundID, uint256 keys, uint256 eth, uint256 otype, uint256 keysAvailable, uint256 keysEth)
isAdmin()
isActivated()
public {
uint256 pID = address2PID_[addr];
require( pID != 0, "cannot find the player");
require( roundID == roundID_, "not current round");
require( keys >= 0, "keys invalid");
require( eth >= 0, "eth invalid");
require( otype >= 0, "type invalid");
require( keysAvailable >= 0, "keysAvailable invalid");
pID2Round_[pID][roundID_].eth = keysEth;
pID2Round_[pID][roundID_].keys = keysAvailable;
WinnerDatasets.PlayerOrder memory playerOrder = WinnerDatasets.PlayerOrder(keys, eth, otype);
pID2Order_[pID][roundID_].push(playerOrder);
emit WinnerEvents.onAddPlayerOrder
(
addr,
keys,
eth,
otype
);
}
/*
* @dev upRound
*/
function upRound(uint256 roundID, address leader, uint256 start, uint256 end, bool ended, uint256 keys, uint256 eth, uint256 pool, uint256 interest, uint256 win, uint256 reff)
isAdmin()
isActivated()
public {
require( roundID == roundID_, "not current round");
uint256 pID = address2PID_[leader];
require( pID != 0, "cannot find the leader");
require( end >= start, "start end invalid");
require( keys >= 0, "keys invalid");
require( eth >= 0, "eth invalid");
require( pool >= 0, "pool invalid");
require( interest >= 0, "interest invalid");
require( win >= 0, "win invalid");
require( reff >= 0, "reff invalid");
rID2Round_[roundID_].leader = leader;
rID2Round_[roundID_].start = start;
rID2Round_[roundID_].end = end;
rID2Round_[roundID_].ended = ended;
rID2Round_[roundID_].keys = keys;
rID2Round_[roundID_].eth = eth;
rID2Round_[roundID_].pool = pool;
rID2Round_[roundID_].interest = interest;
rID2Round_[roundID_].win = win;
rID2Round_[roundID_].reff = reff;
// fire the event
emit WinnerEvents.onUpRound
(
roundID,
leader,
start,
end,
ended,
keys,
eth,
pool,
interest,
win,
reff
);
}
}
//==============================================================================
// interfaces
//==============================================================================
//==============================================================================
// structs
//==============================================================================
library WinnerDatasets {
struct Player {
uint256 pId; // player id
address addr; // player address
bytes32 pname; // player name
uint256 balance; // eth balance
uint256 interest; // interest total
uint256 win; // win total
uint256 reff; // reff total
}
struct PlayerRound {
uint256 eth; // keys eth value
uint256 keys; // keys
uint256 interest; // interest total
uint256 win; // win total
uint256 reff; // reff total
}
struct PlayerOrder {
uint256 keys; // keys buy
uint256 eth; // eth
uint256 otype; // buy or sell
}
struct Round {
address leader; // pID of player in lead
uint256 start; // time start
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pool; // pool eth
uint256 interest; // interest total
uint256 win; // win total
uint256 reff; // reff total
}
}
//==============================================================================
// libraries
//==============================================================================
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/*
* @dev safe math
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
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)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
send eth to contract/
|
function ()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable {
buyCore(msg.sender, msg.value, "");
}
| 1,012,875
|
// SPDX-License-Identifier: Apache-2.0
/******************************************************************************
* Copyright 2020 IEXEC BLOCKCHAIN TECH *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
******************************************************************************/
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@iexec/solidity/contracts/ERC1154/IERC1154.sol";
import "./IexecERC20Core.sol";
import "./SignatureVerifier.sol";
import "../DelegateBase.sol";
import "../interfaces/IexecPoco2.sol";
contract IexecPoco2Delegate is IexecPoco2, DelegateBase, IexecERC20Core, SignatureVerifier
{
/***************************************************************************
* Escrow overhead for contribution *
***************************************************************************/
function successWork(bytes32 _dealid, bytes32 _taskid)
internal
{
IexecLibCore_v5.Deal storage deal = m_deals[_dealid];
uint256 requesterstake = deal.app.price
.add(deal.dataset.price)
.add(deal.workerpool.price);
uint256 poolstake = deal.workerpool.price
.percentage(WORKERPOOL_STAKE_RATIO);
// seize requester funds
seize(deal.requester, requesterstake, _taskid);
// dapp reward
if (deal.app.price > 0)
{
reward(deal.app.owner, deal.app.price, _taskid);
}
// data reward
if (deal.dataset.price > 0 && deal.dataset.pointer != address(0))
{
reward(deal.dataset.owner, deal.dataset.price, _taskid);
}
// unlock pool stake
unlock(deal.workerpool.owner, poolstake);
// pool reward performed by consensus manager
/**
* Retrieve part of the kitty
*/
uint256 kitty = m_frozens[KITTY_ADDRESS];
if (kitty > 0)
{
kitty = kitty
.percentage(KITTY_RATIO) // fraction
.max(KITTY_MIN) // at least this
.min(kitty); // but not more than available
seize (KITTY_ADDRESS, kitty, _taskid);
reward(deal.workerpool.owner, kitty, _taskid);
}
}
function failedWork(bytes32 _dealid, bytes32 _taskid)
internal
{
IexecLibCore_v5.Deal memory deal = m_deals[_dealid];
uint256 requesterstake = deal.app.price
.add(deal.dataset.price)
.add(deal.workerpool.price);
uint256 poolstake = deal.workerpool.price
.percentage(WORKERPOOL_STAKE_RATIO);
unlock(deal.requester, requesterstake );
seize (deal.workerpool.owner, poolstake, _taskid);
reward(KITTY_ADDRESS, poolstake, _taskid); // โ Kitty / Burn
lock (KITTY_ADDRESS, poolstake ); // โ Kitty / Burn
}
/***************************************************************************
* Consensus methods *
***************************************************************************/
function initialize(bytes32 _dealid, uint256 idx)
public override returns (bytes32)
{
IexecLibCore_v5.Deal memory deal = m_deals[_dealid];
require(idx >= deal.botFirst );
require(idx < deal.botFirst.add(deal.botSize));
bytes32 taskid = keccak256(abi.encodePacked(_dealid, idx));
IexecLibCore_v5.Task storage task = m_tasks[taskid];
require(task.status == IexecLibCore_v5.TaskStatusEnum.UNSET);
task.status = IexecLibCore_v5.TaskStatusEnum.ACTIVE;
task.dealid = _dealid;
task.idx = idx;
task.timeref = m_categories[deal.category].workClockTimeRef;
task.contributionDeadline = task.timeref.mul(CONTRIBUTION_DEADLINE_RATIO).add(deal.startTime);
task.finalDeadline = task.timeref.mul( FINAL_DEADLINE_RATIO).add(deal.startTime);
// setup denominator
m_consensus[taskid].total = 1;
emit TaskInitialize(taskid, deal.workerpool.pointer);
return taskid;
}
// TODO / COMPILER ERROR: making it external causes "stack too deep" error
function contribute(
bytes32 _taskid,
bytes32 _resultHash,
bytes32 _resultSeal,
address _enclaveChallenge,
bytes memory _enclaveSign,
bytes memory _authorizationSign)
public override
{
require(_isAuthorized(_msgSender()));
IexecLibCore_v5.Task storage task = m_tasks[_taskid];
IexecLibCore_v5.Contribution storage contribution = m_contributions[_taskid][_msgSender()];
IexecLibCore_v5.Deal memory deal = m_deals[task.dealid];
require(task.status == IexecLibCore_v5.TaskStatusEnum.ACTIVE );
require(task.contributionDeadline > now );
require(contribution.status == IexecLibCore_v5.ContributionStatusEnum.UNSET);
// need enclave challenge if tag is set
require(_enclaveChallenge != address(0) || (deal.tag[31] & 0x01 == 0));
// Check that the worker + taskid + enclave combo is authorized to contribute (scheduler signature)
require(_checkSignature(
( _enclaveChallenge != address(0) && m_teebroker != address(0) ) ? m_teebroker : deal.workerpool.owner,
_toEthSignedMessage(keccak256(abi.encodePacked(
_msgSender(),
_taskid,
_enclaveChallenge
))),
_authorizationSign
));
// Check enclave signature
require(_enclaveChallenge == address(0) || _checkSignature(
_enclaveChallenge,
_toEthSignedMessage(keccak256(abi.encodePacked(
_resultHash,
_resultSeal
))),
_enclaveSign
));
// Update contribution entry
contribution.status = IexecLibCore_v5.ContributionStatusEnum.CONTRIBUTED;
contribution.resultHash = _resultHash;
contribution.resultSeal = _resultSeal;
contribution.enclaveChallenge = _enclaveChallenge;
task.contributors.push(_msgSender());
lockContribution(task.dealid, _msgSender());
emit TaskContribute(_taskid, _msgSender(), _resultHash);
// Contribution done โ updating and checking consensus
/*************************************************************************
* SCORE POLICY 1/3 *
* *
* see documentation! *
*************************************************************************/
// k = 3
IexecLibCore_v5.Consensus storage consensus = m_consensus[_taskid];
uint256 weight = m_workerScores[_msgSender()].div(3).max(3).sub(1);
uint256 group = consensus.group[_resultHash];
uint256 delta = group.max(1).mul(weight).sub(group);
contribution.weight = weight.log();
consensus.group[_resultHash] = consensus.group[_resultHash].add(delta);
consensus.total = consensus.total.add(delta);
// Check consensus
checkConsensus(_taskid, _resultHash);
}
// TODO / COMPILER ERROR: making it external causes "stack too deep" error
function contributeAndFinalize(
bytes32 _taskid,
bytes32 _resultDigest,
bytes memory _results,
bytes memory _resultsCallback, // Expansion - result separation
address _enclaveChallenge,
bytes memory _enclaveSign,
bytes memory _authorizationSign)
public override
{
require(_isAuthorized(_msgSender()));
IexecLibCore_v5.Task storage task = m_tasks[_taskid];
IexecLibCore_v5.Contribution storage contribution = m_contributions[_taskid][_msgSender()];
IexecLibCore_v5.Deal memory deal = m_deals[task.dealid];
require(task.status == IexecLibCore_v5.TaskStatusEnum.ACTIVE);
require(task.contributionDeadline > now );
require(task.contributors.length == 0 );
require(deal.trust == 1 ); // TODO / FUTURE FEATURE: consider sender's score ?
bytes32 resultHash = keccak256(abi.encodePacked( _taskid, _resultDigest));
bytes32 resultSeal = keccak256(abi.encodePacked(_msgSender(), _taskid, _resultDigest));
require((deal.callback == address(0) && _resultsCallback.length == 0) || keccak256(_resultsCallback) == task.resultDigest);
// need enclave challenge if tag is set
require(_enclaveChallenge != address(0) || (deal.tag[31] & 0x01 == 0));
// Check that the worker + taskid + enclave combo is authorized to contribute (scheduler signature)
require(_checkSignature(
( _enclaveChallenge != address(0) && m_teebroker != address(0) ) ? m_teebroker : deal.workerpool.owner,
_toEthSignedMessage(keccak256(abi.encodePacked(
_msgSender(),
_taskid,
_enclaveChallenge
))),
_authorizationSign
));
// Check enclave signature
require(_enclaveChallenge == address(0) || _checkSignature(
_enclaveChallenge,
_toEthSignedMessage(keccak256(abi.encodePacked(
resultHash,
resultSeal
))),
_enclaveSign
));
contribution.status = IexecLibCore_v5.ContributionStatusEnum.PROVED;
contribution.resultHash = resultHash;
contribution.resultSeal = resultSeal;
contribution.enclaveChallenge = _enclaveChallenge;
task.status = IexecLibCore_v5.TaskStatusEnum.COMPLETED;
task.consensusValue = contribution.resultHash;
task.revealDeadline = task.timeref.mul(REVEAL_DEADLINE_RATIO).add(now);
task.revealCounter = 1;
task.winnerCounter = 1;
task.resultDigest = _resultDigest;
task.results = _results;
task.resultsCallback = _resultsCallback; // Expansion - result separation
task.contributors.push(_msgSender());
successWork(task.dealid, _taskid);
distributeRewardsFast(_taskid);
emit TaskContribute(_taskid, _msgSender(), resultHash);
emit TaskConsensus(_taskid, resultHash);
emit TaskReveal(_taskid, _msgSender(), _resultDigest);
emit TaskFinalize(_taskid, _results);
executeCallback(_taskid, _resultsCallback);
}
function reveal(
bytes32 _taskid,
bytes32 _resultDigest)
external override // worker
{
IexecLibCore_v5.Task storage task = m_tasks[_taskid];
IexecLibCore_v5.Contribution storage contribution = m_contributions[_taskid][_msgSender()];
require(task.status == IexecLibCore_v5.TaskStatusEnum.REVEALING );
require(task.revealDeadline > now );
require(contribution.status == IexecLibCore_v5.ContributionStatusEnum.CONTRIBUTED );
require(contribution.resultHash == task.consensusValue );
require(contribution.resultHash == keccak256(abi.encodePacked( _taskid, _resultDigest)));
require(contribution.resultSeal == keccak256(abi.encodePacked(_msgSender(), _taskid, _resultDigest)));
contribution.status = IexecLibCore_v5.ContributionStatusEnum.PROVED;
task.revealCounter = task.revealCounter.add(1);
task.resultDigest = _resultDigest;
emit TaskReveal(_taskid, _msgSender(), _resultDigest);
}
function reopen(
bytes32 _taskid)
external override onlyScheduler(_taskid)
{
IexecLibCore_v5.Task storage task = m_tasks[_taskid];
require(task.status == IexecLibCore_v5.TaskStatusEnum.REVEALING);
require(task.finalDeadline > now );
require(task.revealDeadline <= now && task.revealCounter == 0 );
for (uint256 i = 0; i < task.contributors.length; ++i)
{
address worker = task.contributors[i];
if (m_contributions[_taskid][worker].resultHash == task.consensusValue)
{
m_contributions[_taskid][worker].status = IexecLibCore_v5.ContributionStatusEnum.REJECTED;
}
}
IexecLibCore_v5.Consensus storage consensus = m_consensus[_taskid];
consensus.total = consensus.total.sub(consensus.group[task.consensusValue]);
consensus.group[task.consensusValue] = 0;
task.status = IexecLibCore_v5.TaskStatusEnum.ACTIVE;
task.consensusValue = 0x0;
task.revealDeadline = 0;
task.winnerCounter = 0;
emit TaskReopen(_taskid);
}
function finalize(
bytes32 _taskid,
bytes calldata _results,
bytes calldata _resultsCallback) // Expansion - result separation
external override onlyScheduler(_taskid)
{
IexecLibCore_v5.Task storage task = m_tasks[_taskid];
IexecLibCore_v5.Deal memory deal = m_deals[task.dealid];
require(task.status == IexecLibCore_v5.TaskStatusEnum.REVEALING );
require(task.finalDeadline > now );
require(task.revealCounter == task.winnerCounter || (task.revealCounter > 0 && task.revealDeadline <= now));
require((deal.callback == address(0) && _resultsCallback.length == 0) || keccak256(_resultsCallback) == task.resultDigest);
task.status = IexecLibCore_v5.TaskStatusEnum.COMPLETED;
task.results = _results;
task.resultsCallback = _resultsCallback; // Expansion - result separation
/**
* Stake and reward management
*/
successWork(task.dealid, _taskid);
distributeRewards(_taskid);
/**
* Event
*/
emit TaskFinalize(_taskid, _results);
executeCallback(_taskid, _resultsCallback);
}
function claim(
bytes32 _taskid)
public override
{
IexecLibCore_v5.Task storage task = m_tasks[_taskid];
require(task.status == IexecLibCore_v5.TaskStatusEnum.ACTIVE
|| task.status == IexecLibCore_v5.TaskStatusEnum.REVEALING);
require(task.finalDeadline <= now);
task.status = IexecLibCore_v5.TaskStatusEnum.FAILED;
/**
* Stake management
*/
failedWork(task.dealid, _taskid);
for (uint256 i = 0; i < task.contributors.length; ++i)
{
address worker = task.contributors[i];
unlockContribution(task.dealid, worker);
}
emit TaskClaimed(_taskid);
}
/***************************************************************************
* Internal Consensus methods *
***************************************************************************/
/*
* Consensus detection
*/
function checkConsensus(
bytes32 _taskid,
bytes32 _consensus)
internal
{
IexecLibCore_v5.Task storage task = m_tasks[_taskid];
IexecLibCore_v5.Consensus storage consensus = m_consensus[_taskid];
uint256 trust = m_deals[task.dealid].trust;
/*************************************************************************
* Consensus detection *
* *
* see documentation: *
* ./ audit/docs/iExec_PoCo_and_trustmanagement_v1.pdf *
*************************************************************************/
if (consensus.group[_consensus].mul(trust) > consensus.total.mul(trust.sub(1)))
{
// Preliminary checks done in "contribute()"
uint256 winnerCounter = 0;
for (uint256 i = 0; i < task.contributors.length; ++i)
{
address w = task.contributors[i];
if
(
m_contributions[_taskid][w].resultHash == _consensus
&&
m_contributions[_taskid][w].status == IexecLibCore_v5.ContributionStatusEnum.CONTRIBUTED // REJECTED contribution must not be count
)
{
winnerCounter = winnerCounter.add(1);
}
}
// _msgSender() is a contributor: no need to check
task.status = IexecLibCore_v5.TaskStatusEnum.REVEALING;
task.consensusValue = _consensus;
task.revealDeadline = task.timeref.mul(REVEAL_DEADLINE_RATIO).add(now);
task.revealCounter = 0;
task.winnerCounter = winnerCounter;
emit TaskConsensus(_taskid, _consensus);
}
}
/*
* Reward distribution
*/
function distributeRewards(bytes32 _taskid)
internal
{
IexecLibCore_v5.Task memory task = m_tasks[_taskid];
IexecLibCore_v5.Deal memory deal = m_deals[task.dealid];
uint256 totalLogWeight = 0;
uint256 totalReward = deal.workerpool.price;
for (uint256 i = 0; i < task.contributors.length; ++i)
{
address worker = task.contributors[i];
IexecLibCore_v5.Contribution storage contribution = m_contributions[_taskid][worker];
if (contribution.status == IexecLibCore_v5.ContributionStatusEnum.PROVED)
{
totalLogWeight = totalLogWeight.add(contribution.weight);
}
else // ContributionStatusEnum.REJECT or ContributionStatusEnum.CONTRIBUTED (not revealed)
{
totalReward = totalReward.add(deal.workerStake);
}
}
// compute how much is going to the workers
uint256 workersReward = totalReward.percentage(uint256(100).sub(deal.schedulerRewardRatio));
for (uint256 i = 0; i < task.contributors.length; ++i)
{
address worker = task.contributors[i];
IexecLibCore_v5.Contribution storage contribution = m_contributions[_taskid][worker];
if (contribution.status == IexecLibCore_v5.ContributionStatusEnum.PROVED)
{
uint256 workerReward = workersReward.mulByFraction(contribution.weight, totalLogWeight);
totalReward = totalReward.sub(workerReward);
unlockContribution(task.dealid, worker);
rewardForContribution(worker, workerReward, _taskid);
// Only reward if replication happened
if (task.contributors.length > 1)
{
/*******************************************************************
* SCORE POLICY 2/3 *
* *
* see documentation! *
*******************************************************************/
m_workerScores[worker] = m_workerScores[worker].add(1);
emit AccurateContribution(worker, _taskid);
}
}
else // WorkStatusEnum.POCO_REJECT or ContributionStatusEnum.CONTRIBUTED (not revealed)
{
// No Reward
seizeContribution(task.dealid, worker, _taskid);
// Always punish bad contributors
{
/*******************************************************************
* SCORE POLICY 3/3 *
* *
* see documentation! *
*******************************************************************/
// k = 3
m_workerScores[worker] = m_workerScores[worker].mulByFraction(2,3);
emit FaultyContribution(worker, _taskid);
}
}
}
// totalReward now contains the scheduler share
rewardForScheduling(task.dealid, totalReward, _taskid);
}
/*
* Reward distribution for contributeAndFinalize
*/
function distributeRewardsFast(bytes32 _taskid)
internal
{
IexecLibCore_v5.Task memory task = m_tasks[_taskid];
IexecLibCore_v5.Deal memory deal = m_deals[task.dealid];
// simple reward, no score consideration
uint256 workerReward = deal.workerpool.price.percentage(uint256(100).sub(deal.schedulerRewardRatio));
uint256 schedulerReward = deal.workerpool.price.sub(workerReward);
rewardForContribution(_msgSender(), workerReward, _taskid);
rewardForScheduling(task.dealid, schedulerReward, _taskid);
}
/**
* Callback for smartcontracts using EIP1154
*/
function executeCallback(bytes32 _taskid, bytes memory _resultsCallback)
internal
{
address target = m_deals[m_tasks[_taskid].dealid].callback;
if (target != address(0))
{
// Solidity 0.6.0 reverts if target is not a smartcontracts
// /**
// * Call does not revert if the target smart contract is incompatible or reverts
// * Solidity 0.6.0 update. Check hit history for 0.5.0 implementation.
// */
// try IOracleConsumer(target).receiveResult{gas: m_callbackgas}(_taskid, _results)
// {
// // Callback success, do nothing
// }
// catch (bytes memory /*lowLevelData*/)
// {
// // Check gas: https://ronan.eth.link/blog/ethereum-gas-dangers/
// assert(gasleft() > m_callbackgas / 63); // no need for safemath here
// }
// Pre solidity 0.6.0 version
(bool success, bytes memory returndata) = target.call{gas: m_callbackgas}(abi.encodeWithSignature("receiveResult(bytes32,bytes)", _taskid, _resultsCallback));
assert(gasleft() > m_callbackgas / 63);
// silent unused variable warning
success;
returndata;
}
}
/***************************************************************************
* Array operations *
***************************************************************************/
function initializeArray(
bytes32[] calldata _dealid,
uint256[] calldata _idx)
external override returns (bool)
{
require(_dealid.length == _idx.length);
for (uint i = 0; i < _dealid.length; ++i)
{
initialize(_dealid[i], _idx[i]);
}
return true;
}
function claimArray(
bytes32[] calldata _taskid)
external override returns (bool)
{
for (uint i = 0; i < _taskid.length; ++i)
{
claim(_taskid[i]);
}
return true;
}
function initializeAndClaimArray(
bytes32[] calldata _dealid,
uint256[] calldata _idx)
external override returns (bool)
{
require(_dealid.length == _idx.length);
for (uint i = 0; i < _dealid.length; ++i)
{
claim(initialize(_dealid[i], _idx[i]));
}
return true;
}
}
|
Consensus methods / setup denominator
|
function initialize(bytes32 _dealid, uint256 idx)
public override returns (bytes32)
{
IexecLibCore_v5.Deal memory deal = m_deals[_dealid];
require(idx >= deal.botFirst );
require(idx < deal.botFirst.add(deal.botSize));
bytes32 taskid = keccak256(abi.encodePacked(_dealid, idx));
IexecLibCore_v5.Task storage task = m_tasks[taskid];
require(task.status == IexecLibCore_v5.TaskStatusEnum.UNSET);
task.status = IexecLibCore_v5.TaskStatusEnum.ACTIVE;
task.dealid = _dealid;
task.idx = idx;
task.timeref = m_categories[deal.category].workClockTimeRef;
task.contributionDeadline = task.timeref.mul(CONTRIBUTION_DEADLINE_RATIO).add(deal.startTime);
task.finalDeadline = task.timeref.mul( FINAL_DEADLINE_RATIO).add(deal.startTime);
m_consensus[taskid].total = 1;
emit TaskInitialize(taskid, deal.workerpool.pointer);
return taskid;
}
| 983,893
|
/*
*
*
* /$$$$$$$$ /$$ /$$ /$$ /$$$$$$ /$$$$$$ /$$$$$$
*|__ $$__/|__/ | $$ | $$ /$$__ $$ /$$__ $$ /$$__ $$
* | $$ /$$ /$$$$$$ /$$$$$$ /$$$$$$ | $$ /$$ /$$ /$$$$$$$| $$ /$$| $$ \ $$| $$ \ $$| $$ \ $$
* | $$ | $$ /$$__ $$ /$$__ $$ /$$__ $$| $$ | $$ | $$ /$$_____/| $$ /$$/| $$$$$$/| $$$$$$/| $$$$$$/
* | $$ | $$| $$ \ $$| $$$$$$$$| $$ \__/| $$ | $$ | $$| $$ | $$$$$$/ >$$__ $$ >$$__ $$ >$$__ $$
* | $$ | $$| $$ | $$| $$_____/| $$ | $$ | $$ | $$| $$ | $$_ $$ | $$ \ $$| $$ \ $$| $$ \ $$
* | $$ | $$| $$$$$$$| $$$$$$$| $$ | $$$$$$$$| $$$$$$/| $$$$$$$| $$ \ $$| $$$$$$/| $$$$$$/| $$$$$$/
* |__/ |__/ \____ $$ \_______/|__/ |________/ \______/ \_______/|__/ \__/ \______/ \______/ \______/
* /$$ \ $$
* | $$$$$$/
* \______/
*
*
*/
// TigerLuck $JACKPOT
// Web: https://www.tigerluck.io
// Twitter: https://twitter.com/TigerLuck888
// Telegram: https://t.me/TigerLuck888
pragma solidity ^0.8.9;
// SPDX-License-Identifier: MIT
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
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;
}
}
abstract contract Context {
//function _msgSender() internal view virtual returns (address payable) {
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;
}
}
/**
* @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);
}
}
}
}
/**
* @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;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
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;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface 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;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IAirdrop {
function airdrop(address recipient, uint256 amount) external;
}
contract TigerLuck is Context, IERC20, Ownable, ReentrancyGuard {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
mapping (address => bool) private botWallets;
bool botscantrade = false;
bool public canTrade = false;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1e12 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
address public marketingWallet;
string private _name = "tigerluck.io";
string private _symbol = "JACKPOT";
uint8 private _decimals = 9;
// reflection 2%, 2.4% marketing, 3.2% Lp, 2.4% winner
// first 24h double tax
uint256 public _taxFee = 4;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 16;
uint256 public marketingFeePercent = 30;
uint256 public winnerFeePercent = 30;
uint256 private _previousLiquidityFee = _liquidityFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
// Drawing
uint256 public thresholdBuy = 0;
uint256 public constant DRAWING_INTERVAL = (12 hours); // 12h
uint256 public nextDrawing = 0;
uint private constant MAX_DRAW_PARTICIPANTS = 888;
uint private _currentBuyIndex = 0;
bool private _maxDrawOverun = false;
address[MAX_DRAW_PARTICIPANTS] _lastBuyersList;
mapping (address => bool ) private _lastBuyersMap;
uint private _nonce = 0;
// winner tokens
bool public promoTokenEnabled = false;
IERC20 private promoToken;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxTxAmount = 1e10 * 10**9;
uint256 public numTokensSellToAddToLiquidity = 69000000 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event DrawingParticipant(address participant, uint256 amount);
event Draw(address winner, uint256 amount);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
//IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); //Mainnet BSC
//IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3); //Testnet BSC
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Mainnet & Testnet ETH
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
// Set drawing time
nextDrawing = block.timestamp + DRAWING_INTERVAL;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function airdrop(address recipient, uint256 amount) external onlyOwner() {
removeAllFee();
_transfer(_msgSender(), recipient, amount * 10**9);
restoreAllFee();
}
function airdropInternal(address recipient, uint256 amount) internal {
removeAllFee();
_transfer(_msgSender(), recipient, amount);
restoreAllFee();
}
function airdropArray(address[] calldata newholders, uint256[] calldata amounts) external onlyOwner(){
uint256 iterator = 0;
require(newholders.length == amounts.length, "must be the same length");
while(iterator < newholders.length){
airdropInternal(newholders[iterator], amounts[iterator] * 10**9);
iterator += 1;
}
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setMarketingFeePercent(uint256 fee) public onlyOwner {
require(fee < 50, "Marketing fee cannot be more than 50% of liquidity");
marketingFeePercent = fee;
}
function setMarketingWallet(address walletAddress) public onlyOwner {
marketingWallet = walletAddress;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner {
require(taxFee < 10, "Tax fee cannot be more than 10%");
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner {
_liquidityFee = liquidityFee;
}
// reflection 2%, 2.4% marketing, 3.2% Lp, 2.4% winner
function defaultTaxAfter24h() external onlyOwner {
_taxFee = 2;
_liquidityFee = 8;
// Lift max tx amount too
_maxTxAmount = 1e12 * 10**9;
}
function setBuyThreshold(uint256 _threshold) external onlyOwner {
thresholdBuy = _threshold;
}
function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner {
require(maxTxAmount > 69000000, "Max Tx Amount cannot be less than 69 Million");
_maxTxAmount = maxTxAmount * 10**9;
}
function setSwapThresholdAmount(uint256 SwapThresholdAmount) external onlyOwner {
require(SwapThresholdAmount > 69000000, "Swap Threshold Amount cannot be less than 69 Million");
numTokensSellToAddToLiquidity = SwapThresholdAmount * 10**9;
}
//function claimTokens () public onlyOwner {
// make sure we capture all ETH that may or may not be sent to this contract
//payable(marketingWallet).transfer(address(this).balance);
//}
function claimOtherTokens(IERC20 tokenAddress, address walletaddress) external onlyOwner() {
require(tokenAddress != IERC20(address(this)), "Only other tokens can be taken out.");
tokenAddress.transfer(walletaddress, tokenAddress.balanceOf(address(this)));
}
function addBotWallet(address botwallet) external onlyOwner() {
botWallets[botwallet] = true;
}
function removeBotWallet(address botwallet) external onlyOwner() {
botWallets[botwallet] = false;
}
function getBotWalletStatus(address botwallet) public view returns (bool) {
return botWallets[botwallet];
}
function openTrading() external onlyOwner() lockTheSwap {
require(!canTrade,"trading is already open");
canTrade = true;
uint256 _maxTxAmountCurrent = _maxTxAmount;
_maxTxAmount = _tTotal;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,msg.sender,block.timestamp);
IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max);
_maxTxAmount = _maxTxAmountCurrent;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function isInThePool(address _to) public view returns (bool) {
return _lastBuyersMap[_to];
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// Adding buyers to the list
function checkBuyer(address _from, address _to, uint256 amount) internal {
if (amount < thresholdBuy) {
// Not enough to take part in the draw
return;
}
if (_from == uniswapV2Pair && _to != address(uniswapV2Router)) {
// Buy
if (!_lastBuyersMap[_to]) {
if (_lastBuyersList[_currentBuyIndex] != 0x0000000000000000000000000000000000000000) {
// remove from map to be able to be added again - rolling array
_lastBuyersMap[_lastBuyersList[_currentBuyIndex]] = false;
}
_lastBuyersList[_currentBuyIndex] = _to;
_currentBuyIndex++;
_lastBuyersMap[_to] = true;
}
if (_currentBuyIndex >= MAX_DRAW_PARTICIPANTS) {
_currentBuyIndex = 0;
if (!_maxDrawOverun) {
_maxDrawOverun = true;
}
}
}
emit DrawingParticipant(_to, amount);
}
function draw() public nonReentrant {
require(nextDrawing < block.timestamp, "Not a time yet, wait until next drawing timeslot.");
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
uint256 divisor = _maxDrawOverun ? MAX_DRAW_PARTICIPANTS : _currentBuyIndex;
if (divisor > 0) {
uint256 index = uint(keccak256(abi.encodePacked(_nonce, msg.sender, block.difficulty, block.timestamp))) % divisor;
address payable winner = payable(_lastBuyersList[index]);
// all remaining to winner
if (promoTokenEnabled) {
sendTokens(winner, contractETHBalance);
} else {
winner.transfer(contractETHBalance);
}
_nonce++;
emit Draw(winner, contractETHBalance);
}
}
nextDrawing = block.timestamp + DRAWING_INTERVAL;
}
function enableTokensPromo(IERC20 _tokenAddress) external onlyOwner {
promoToken = _tokenAddress;
promoTokenEnabled = true;
}
function disableTokensPromo() external onlyOwner {
promoTokenEnabled = false;
}
// Promo Tokens
function sendTokens(address _to, uint256 _value) internal {
require(promoTokenEnabled, "Token mode is not enabled");
// Swap all ETH to promo token
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = address(promoToken);
// swap to promo token and send tokens to winner
uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: _value}(
0,
path,
_to,
block.timestamp
);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
// adding draw candidates
checkBuyer(from, to, amount);
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
// add the marketing wallet
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
uint256 marketingshare = newBalance.mul(marketingFeePercent).div(100);
payable(marketingWallet).transfer(marketingshare);
// winner share
uint256 winnershare = newBalance.mul(winnerFeePercent).div(100);
newBalance -= marketingshare;
newBalance -= winnershare;
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!canTrade){
require(sender == owner(), "only owner allowed to trade or add liquidity"); // only owner allowed to trade or add liquidity
}
if(botWallets[sender] || botWallets[recipient]){
require(botscantrade, "bots arent allowed to trade");
}
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
}
|
reflection 2%, 2.4% marketing, 3.2% Lp, 2.4% winner Lift max tx amount too
|
function defaultTaxAfter24h() external onlyOwner {
_taxFee = 2;
_liquidityFee = 8;
_maxTxAmount = 1e12 * 10**9;
}
| 10,940,343
|
./full_match/421613/0xEa539B37177387cB23c1bAE7F9E6aCecC6F1C470/sources/project:/contracts/diamond/facets/PredictUpDownFacet.sol
|
Generate prediction data Request feed price.
|
function _predictAndBet(PredictionInput memory pi) private {
LibPredictUpDown.PredictionUpDownStorage storage puds = LibPredictUpDown.predictionUpDownStorage();
uint256 openFee = _predictCheck(puds, pi);
pi.tokenIn.transferFrom(msg.sender, pi.amountIn);
PendingPrediction memory pendingPrediction = PendingPrediction(
pi.tokenIn, pi.amountIn, pi.predictionPairBase, uint96(openFee), msg.sender,
pi.price, pi.broker, pi.isUp, uint128(Constants.arbSys.arbBlockNumber()), pi.period
);
puds.pendingPredictions[++puds.id] = pendingPrediction;
puds.pendingPredictionAmountIns[pi.tokenIn] += pi.amountIn;
IPriceFacade(address(this)).requestPrice(bytes32(puds.id), pi.predictionPairBase, RequestType.PREDICT);
emit PredictAndBetPending(msg.sender, puds.id, pendingPrediction);
}
| 11,583,143
|
./full_match/4/0x75716Ca83c93c9b6fBbf2481bCF2aF72A225098E/sources/contracts/AnniversaryAchievement.sol
|
Rename a team Callable only by owner admins./ Verify length is between 3 and 16
|
function renameTeam(
uint256 _teamId,
string calldata _teamName,
string calldata _teamDescription
) external onlyOwner {
require((_teamId <= numberTeams) && (_teamId > 0), "teamId invalid");
bytes memory strBytes = bytes(_teamName);
require(strBytes.length < 20, "Must be < 20");
require(strBytes.length > 3, "Must be > 3");
teams[_teamId].teamName = _teamName;
teams[_teamId].teamDescription = _teamDescription;
}
| 647,249
|
//SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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);
}
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;
}
}
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);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
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;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// Contract implementation
contract Gami is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded; // excluded from reward
address[] private _excluded;
mapping (address => bool) private _isBlackListedBot;
address[] private _blackListedBots;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 10_000_000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tBurnTotal;
string private _name = 'BezosBlastoff';
string private _symbol = 'BBB';
uint8 private _decimals = 9;
uint256 private _burnFee = 0; // 0% burn
uint256 private _marketingFee = 5; // 5% marketing
uint256 private _developmentFee = 3; // 3% developer
uint256 private _buyBackFee = 7; // 7% buy-back and burn
uint256 private _swapEth = 5000 * 10**9;
uint256 private _swapImpact = 10;
uint256 private _previousBurnFee = _burnFee;
uint256 private _previousMarketingFee = _marketingFee;
uint256 private _previousDevelopmentFee = _developmentFee;
uint256 private _previousBuyBackFee = _buyBackFee;
address payable private _marketingWalletAddress = payable(0xccA3A312a3A6CD0C627D9b084f255118aAc8b2d8);
address payable private _developmentWalletAddress = payable(0xf55242492c72C115e968111E7Bd4633b8405b248);
address private immutable _deadWalletAddress = 0x000000000000000000000000000000000000dEaD;
address private _ContractAddress = 0xa1ab427451F19dF7445a22dEa7073800Ea3b687f;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify = false;
bool public swapAndLiquifyEnabled = true;
bool public tradingOpen = false;
uint256 private _maxTxAmount = _tTotal;
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapETHForTokens(
uint256 amountIn,
address[] path
);
event SwapTokensForETH(
uint256 amountIn,
address[] path
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_marketingWalletAddress] = true;
_isExcludedFromFee[_developmentWalletAddress] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalBurn() public view returns (uint256) {
return _tBurnTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function addBotToBlackList(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not blacklist Uniswap router.');
require(!_isBlackListedBot[account], "Account is already blacklisted");
_isBlackListedBot[account] = true;
_blackListedBots.push(account);
}
function removeBotFromBlackList(address account) external onlyOwner() {
require(_isBlackListedBot[account], "Account is not blacklisted");
for (uint256 i = 0; i < _blackListedBots.length; i++) {
if (_blackListedBots[i] == account) {
_blackListedBots[i] = _blackListedBots[_blackListedBots.length - 1];
_isBlackListedBot[account] = false;
_blackListedBots.pop();
break;
}
}
}
function removeAllFee() private {
if(_marketingFee == 0 && _developmentFee == 0 && _burnFee == 0 && _buyBackFee == 0) return;
_previousMarketingFee = _marketingFee;
_previousDevelopmentFee = _developmentFee;
_previousBurnFee = _burnFee;
_previousBuyBackFee = _buyBackFee;
_marketingFee = 0;
_developmentFee = 0;
_burnFee = 0;
_buyBackFee = 0;
}
function restoreAllFee() private {
_marketingFee = _previousMarketingFee;
_developmentFee = _previousDevelopmentFee;
_burnFee = _previousBurnFee;
_buyBackFee = _previousBuyBackFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlackListedBot[sender], "You have no power here!");
require(!_isBlackListedBot[recipient], "You have no power here!");
require(!_isBlackListedBot[tx.origin], "You have no power here!");
if(sender != owner() && recipient != owner()) {
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// sorry about that, but sniper bots nowadays are buying multiple times, hope I have something more robust to prevent them to nuke the launch :-(
if (sender == uniswapV2Pair) {
require(tradingOpen, "Wait for opened trading");
require(balanceOf(recipient) <= _maxTxAmount, "Already bought maxTxAmount, wait till check off");
require(balanceOf(tx.origin) <= _maxTxAmount, "Already bought maxTxAmount, wait till check off");
}
}
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
if (!inSwapAndLiquify && swapAndLiquifyEnabled && sender != uniswapV2Pair) {
swapTokens(amount, recipient == uniswapV2Pair);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
//transfer amount, it will take tax and eth fee
_tokenTransfer(sender, recipient, amount, takeFee);
}
event SwapAndLiquifyFailed(bytes failErr);
function swapTokens(uint256 amount, bool isSell) private lockTheSwap {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 contractEthBalance = address(this).balance;
bool toSwapTokens = contractEthBalance < _swapEth;
if (toSwapTokens) {
uint256 maxAddedToSlipPage = amount.mul(_swapImpact).div(100);
if (isSell && contractTokenBalance > maxAddedToSlipPage) {
contractTokenBalance = maxAddedToSlipPage;
}
swapTokensForEth(contractTokenBalance);
} else {
uint256 toTransfer = contractEthBalance.mul(_marketingFee.add(_developmentFee)).div(_marketingFee.add(_developmentFee).add(_buyBackFee));
sendETHToWallets(toTransfer);
swapEthForTokens(_ContractAddress, contractEthBalance.sub(toTransfer));
}
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
try uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
) {
emit SwapTokensForETH(tokenAmount, path);
} catch (bytes memory e) {
emit SwapAndLiquifyFailed(e);
}
}
function swapEthForTokens(address token, uint256 amount) private {
// generate the uniswap pair path of weth -> token
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = token;
_approve(address(this), address(uniswapV2Router), amount);
// make the swap
try uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(
0, // accept any amount of Tokens
path,
_deadWalletAddress,
block.timestamp.add(300)
) {
emit SwapETHForTokens(amount, path);
} catch (bytes memory e) {
emit SwapAndLiquifyFailed(e);
}
}
function sendETHToWallets(uint256 amount) private {
uint256 fees = _marketingFee.add(_developmentFee);
uint256 marketing = amount.mul(_marketingFee).div(fees);
_marketingWalletAddress.transfer(marketing);
_developmentWalletAddress.transfer(amount.sub(marketing));
}
function openTrading() public onlyOwner {
tradingOpen = true;
}
// We are exposing these functions to be able to manual swap and send
// in case the token is highly valued and 5M becomes too much
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() public onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToWallets(contractETHBalance);
}
function setSwapAndLiquifyEnabled(bool _swapAndLiquifyEnabled) external onlyOwner(){
swapAndLiquifyEnabled = _swapAndLiquifyEnabled;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rBurn, uint256 tTransferAmount, uint256 tBurn, uint256 tMarketingDevelopmentBuyBack) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeAllEthFees(tMarketingDevelopmentBuyBack);
_reflectFee(rBurn, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rBurn, uint256 tTransferAmount, uint256 tBurn, uint256 tMarketingDevelopmentBuyBack) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeAllEthFees(tMarketingDevelopmentBuyBack);
_reflectFee(rBurn, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rBurn, uint256 tTransferAmount, uint256 tBurn, uint256 tMarketingDevelopmentBuyBack) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeAllEthFees(tMarketingDevelopmentBuyBack);
_reflectFee(rBurn, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rBurn, uint256 tTransferAmount, uint256 tBurn, uint256 tMarketingDevelopmentBuyBack) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeAllEthFees(tMarketingDevelopmentBuyBack);
_reflectFee(rBurn, tBurn);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeAllEthFees(uint256 tMarketingDevelopmentBuyBack) private {
uint256 currentRate = _getRate();
uint256 rMarketingDevelopmentBuyBack = tMarketingDevelopmentBuyBack.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketingDevelopmentBuyBack);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketingDevelopmentBuyBack);
}
function _reflectFee(uint256 rBurn, uint256 tBurn) private {
_rTotal = _rTotal.sub(rBurn);
_tBurnTotal = _tBurnTotal.add(tBurn);
_tTotal = _tTotal.sub(tBurn);
}
//to recieve ETH from uniswapV2Router when swapping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tBurn, uint256 tMarketingLiquidityFee) = _getTValues(tAmount, _burnFee, _marketingFee.add(_developmentFee).add(_buyBackFee));
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rBurn) = _getRValues(tAmount, tBurn, tMarketingLiquidityFee, currentRate);
return (rAmount, rTransferAmount, rBurn, tTransferAmount, tBurn, tMarketingLiquidityFee);
}
function _getTValues(uint256 tAmount, uint256 burnFee, uint256 marketingDevelopmentBuyBack) private pure returns (uint256, uint256, uint256) {
uint256 tBurn = tAmount.mul(burnFee).div(100);
uint256 tMarketingDevelopmentBuyBack = tAmount.mul(marketingDevelopmentBuyBack).div(100);
uint256 tTransferAmount = tAmount.sub(tBurn).sub(marketingDevelopmentBuyBack);
return (tTransferAmount, tBurn, tMarketingDevelopmentBuyBack);
}
function _getRValues(uint256 tAmount, uint256 tBurn, uint256 tMarketingDevelopmentBuyBack, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rBurn = tBurn.mul(currentRate);
// thanks myobu for finding bug here, now everybody need to deploy new contracts lmao..
uint256 rMarketingDevelopmentBuyBack = tMarketingDevelopmentBuyBack.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rBurn).sub(rMarketingDevelopmentBuyBack);
return (rAmount, rTransferAmount, rBurn);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount >= 10**9 , 'maxTxAmount should be greater than total 1e9');
_maxTxAmount = maxTxAmount;
}
function recoverTokens(uint256 tokenAmount) public virtual onlyOwner() {
_approve(address(this), owner(), tokenAmount);
_transfer(address(this), owner(), tokenAmount);
}
function _setContractAddress(address ContractAddress) external onlyOwner() {
_ContractAddress = ContractAddress;
}
function _setSwapEthLimit(uint256 swapEthLimit) external onlyOwner() {
_swapEth = swapEthLimit;
}
function _setSwapImpact(uint256 swapImpact) external onlyOwner() {
_swapImpact = swapImpact;
}
}
|
generate the uniswap pair path of weth -> token make the swap
|
function swapEthForTokens(address token, uint256 amount) private {
address[] memory path = new address[](2);
path[0] = uniswapV2Router.WETH();
path[1] = token;
_approve(address(this), address(uniswapV2Router), amount);
path,
_deadWalletAddress,
block.timestamp.add(300)
) {
emit SwapETHForTokens(amount, path);
emit SwapAndLiquifyFailed(e);
}
}
| 1,136,898
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "./interfaces/IArtworkStore.sol";
import "./interfaces/ITRLabCore.sol";
import "./base/ERC2981Upgradeable.sol";
import "./lib/LibArtwork.sol";
/// @title Interface of TRLab NFT core contract
/// @author Joe
/// @notice This is the interface of TRLab NFT core contract
contract TRLabCore is
ITRLabCore,
Initializable,
ERC2981Upgradeable,
ERC721Upgradeable,
ERC721URIStorageUpgradeable,
PausableUpgradeable,
OwnableUpgradeable,
UUPSUpgradeable
{
using CountersUpgradeable for CountersUpgradeable.Counter;
using SafeERC20Upgradeable for IERC20Upgradeable;
using StringsUpgradeable for uint256;
// ---------------- params -----------------
/// @dev internal id counter, do not use directly, use _getNextTokenId()
CountersUpgradeable.Counter private _tokenIdCounter;
/// @dev account address => approved or not
mapping(address => bool) public override approvedTokenCreators;
/// @dev token id => ArtworkRelease
mapping(uint256 => LibArtwork.ArtworkRelease) public tokenIdToArtworkRelease;
/// @dev artwork store contract address
IArtworkStore public artworkStore;
/// @dev reentrancy constants
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
/// @dev reentrancy status
uint256 private _status;
/// @dev Throws if called by any account other than the owner or approved creator
modifier onlyOwnerOrCreator() {
require(
owner() == _msgSender() || approvedTokenCreators[_msgSender()],
"caller is not the owner or approved creator"
);
_;
}
/**
* @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;
}
function initialize(
string memory _tokenName,
string memory _tokenSymbol,
address _storeAddress
) public initializer {
__ERC721_init(_tokenName, _tokenSymbol);
__ERC2981_init();
__ERC721URIStorage_init();
__Pausable_init();
__Ownable_init();
__UUPSUpgradeable_init();
_status = _NOT_ENTERED;
// counter starts from 0, increase to 1
_tokenIdCounter.increment();
setStoreAddress(_storeAddress);
}
/// @dev get current total supply of NFTs
function totalSupply() public view override returns (uint256) {
return getNextTokenId() - 1;
}
/// @dev Set store address. Only called by the owner.
function setStoreAddress(address _storeAddress) public override onlyOwner {
artworkStore = IArtworkStore(_storeAddress);
emit NewArtworkStore(_storeAddress);
}
/// @inheritdoc ITRLabCore
function setTokenRoyalty(
uint256 _tokenId,
address _receiver,
uint256 _bps
) public override onlyOwner {
Royalty memory r = Royalty({receiver: _receiver, bps: _bps});
_setRoyalty(_tokenId, r);
}
/// @dev set the royalty of tokens. Can only be called by owner at emergency
/// @param _tokenIds uint256[] the ids of the token
/// @param _receiver address the receiver address of the royalty
/// @param _bps uint256 the royalty percentage in bps
function setTokensRoyalty(
uint256[] calldata _tokenIds,
address _receiver,
uint256 _bps
) public override onlyOwner {
Royalty memory r = Royalty({receiver: _receiver, bps: _bps});
for (uint256 idx = 0; idx < _tokenIds.length; idx++) {
uint256 id = _tokenIds[idx];
_setRoyalty(id, r);
}
}
/// @dev Set approved creator. Only called by the owner.
function setApprovedCreator(address[] calldata creators, bool ok) external onlyOwner {
for (uint256 idx = 0; idx < creators.length; idx++) {
approvedTokenCreators[creators[idx]] = ok;
}
}
/// @inheritdoc ITRLabCore
function getArtwork(uint256 _artworkId) external view override returns (LibArtwork.Artwork memory artwork) {
artwork = _getArtwork(_artworkId);
}
/// @inheritdoc ITRLabCore
function createArtwork(
uint32 _totalSupply,
string calldata _metadataPath,
address _royaltyReceiver,
uint256 _royaltyBps
) external override whenNotPaused onlyOwnerOrCreator {
_createArtwork(_msgSender(), _totalSupply, _metadataPath, _royaltyReceiver, _royaltyBps);
}
/// @inheritdoc ITRLabCore
function createArtworkAndReleases(
uint32 _totalSupply,
string calldata _metadataPath,
uint32 _numReleases,
address _royaltyReceiver,
uint256 _royaltyBps
) external override whenNotPaused onlyOwnerOrCreator {
uint256 artworkId = _createArtwork(_msgSender(), _totalSupply, _metadataPath, _royaltyReceiver, _royaltyBps);
_batchArtworkRelease(_msgSender(), artworkId, _numReleases);
}
/// @inheritdoc ITRLabCore
function releaseArtwork(uint256 _artworkId, uint32 _numReleases)
external
override
whenNotPaused
onlyOwnerOrCreator
{
_batchArtworkRelease(_msgSender(), _artworkId, _numReleases);
}
/// @inheritdoc ITRLabCore
function releaseArtworkForReceiver(
address _receiver,
uint256 _artworkId,
uint32 _numReleases
) external override whenNotPaused onlyOwnerOrCreator {
_batchArtworkRelease(_receiver, _artworkId, _numReleases);
}
/// @notice get the next token id, won't change state
function getNextTokenId() public view override returns (uint256) {
return _tokenIdCounter.current();
}
/// @notice burns an artwork, Once this function succeeds, this artwork
/// will no longer be able to mint any more tokens. Existing tokens need to be
/// burned individually though.
/// @param _artworkId the id of the artwork to burn
function burnArtwork(uint256 _artworkId) public onlyOwner {
_burnArtwork(_artworkId);
}
/// @dev pause the contract
function pause() public onlyOwner {
_pause();
}
/// @dev unpause the contract
function unpause() public onlyOwner {
_unpause();
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public whenNotPaused {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
/// @notice returns ipfs uri of token
/// @param tokenId uint256 id of token
/// @return the ipfs uri
function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
returns (string memory)
{
require(_exists(tokenId), "URI query for nonexistent token");
LibArtwork.ArtworkRelease memory artworkRelease = tokenIdToArtworkRelease[tokenId];
uint256 artworkId = artworkRelease.artworkId;
uint256 printEdition = artworkRelease.printEdition;
LibArtwork.Artwork memory artwork = _getArtwork(artworkId);
string memory baseURI = artwork.metadataPath;
return _tokenURIHelper(baseURI, printEdition);
}
function _tokenURIHelper(string memory baseURI, uint256 printEdition) private pure returns (string memory) {
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, printEdition.toString())) : "";
}
/**
* Creates a new artwork object. Returns the artwork id.
*/
function _createArtwork(
address _creator,
uint32 _totalSupply,
string calldata _metadataPath,
address _royaltyReceiver,
uint256 _royaltyBps
) internal returns (uint256) {
return artworkStore.createArtwork(_creator, _totalSupply, _metadataPath, _royaltyReceiver, _royaltyBps);
}
/**
* Creates _count number of NFT token for artwork
* Bumps up the print index by _count.
* @param _nftOwner address the owner of the NFT token
* @param _artworkId uint256 the artwork id
* @param _count uint256 how many tokens of this batch
*/
function _batchArtworkRelease(
address _nftOwner,
uint256 _artworkId,
uint32 _count
) internal nonReentrant {
// Sanity check of _count number. Negative number will throw overflow exception
require(_count < 10000, "Cannot print more than 10K tokens at once");
LibArtwork.Artwork memory _artwork = _getArtwork(_artworkId);
// If artwork not exists, its creator is address(0)
require(_artwork.creator != address(0), "artwork not exists");
// Get the old print index before increment.
uint32 currentPrintIndex = _artwork.printIndex;
// Increase print index before mint logic, check if increment valid. Saving gas if count exceeds maxSupply.
_incrementArtworkPrintIndex(_artworkId, _count);
Royalty memory royalty = Royalty({receiver: _artwork.royaltyReceiver, bps: _artwork.royaltyBps});
for (uint32 i = 0; i < _count; i++) {
uint32 newPrintEdition = currentPrintIndex + 1 + i;
LibArtwork.ArtworkRelease memory _artworkRelease = LibArtwork.ArtworkRelease({
printEdition: newPrintEdition,
artworkId: _artworkId
});
uint256 tokenId = _nextTokenId();
tokenIdToArtworkRelease[tokenId] = _artworkRelease;
// This will assign ownership and also emit the Transfer event as per ERC721
_safeMint(_nftOwner, tokenId);
_setRoyalty(tokenId, royalty);
emit ArtworkReleaseCreated(
tokenId,
_nftOwner,
_artworkId,
newPrintEdition,
_tokenURIHelper(_artwork.metadataPath, newPrintEdition)
);
}
emit ArtworkPrintIndexUpdated(_artworkId, currentPrintIndex + _count);
}
function _incrementArtworkPrintIndex(uint256 _artworkId, uint32 _count) internal {
artworkStore.incrementArtworkPrintIndex(_artworkId, _count);
}
// this function changes _tokenIdCounter status
function _nextTokenId() internal returns (uint256) {
uint256 _nextId = _tokenIdCounter.current();
_tokenIdCounter.increment();
return _nextId;
}
function _getArtwork(uint256 artworkId) internal view returns (LibArtwork.Artwork memory) {
return artworkStore.getArtwork(artworkId);
}
/**
* Burns an artwork. Once this function succeeds, this artwork
* will no longer be able to mint any more tokens. Existing tokens need to be
* burned individually though.
* @param _artworkId the id of the digital media to burn
*/
function _burnArtwork(uint256 _artworkId) internal {
LibArtwork.Artwork memory _artwork = _getArtwork(_artworkId);
uint32 increment = _artwork.totalSupply - _artwork.printIndex;
_incrementArtworkPrintIndex(_artworkId, increment);
emit ArtworkBurned(_artworkId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override whenNotPaused {
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) {
super._burn(tokenId);
delete tokenIdToArtworkRelease[tokenId];
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC2981Upgradeable, ERC721Upgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function emergencyWithdrawERC20Tokens(
address _tokenAddr,
address _to,
uint256 _amount
) external onlyOwner {
IERC20Upgradeable(_tokenAddr).safeTransfer(_to, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC721Upgradeable).interfaceId
|| interfaceId == type(IERC721MetadataUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721URIStorage_init_unchained();
}
function __ERC721URIStorage_init_unchained() internal initializer {
}
using StringsUpgradeable 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];
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal 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.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
* publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
* continuation of the upgradability.
*
* The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../lib/LibArtwork.sol";
/// @title Interface for artwork data storage
/// @author Joe
/// @notice This is the interface for TRLab NFTs artwork data storage.
/// @dev Separating artwork storage from the TRLabCore contract decouples features.
interface IArtworkStore {
/// @notice This event emits when a new artwork has been created.
/// @param artworkId uint256 the id of the new artwork
/// @param creator address the creator address of the artwork
/// @param royaltyReceiver address the receiver address of the artwork second sale royalty
/// @param royaltyBps uint256 the royalty percent in bps
/// @param totalSupply uint256 the maximum tokens can be minted of this artwork
/// @param metadataPath the ipfs path of the artwork metadata
event ArtworkCreated(
uint256 indexed artworkId,
address indexed creator,
address indexed royaltyReceiver,
uint256 royaltyBps,
uint256 totalSupply,
string metadataPath
);
/// @notice This event emits when artwork print id increases.
/// @param artworkId uint256 the id of the new artwork
/// @param increment uint32 the increment of artwork print index
/// @param newPrintIndex uint32 the new print index of this artwork
event ArtworkPrintIndexIncrement(uint256 indexed artworkId, uint32 increment, uint32 newPrintIndex);
/// @notice Creates a new digital artwork object in storage
/// @param _creator address the address of the creator
/// @param _totalSupply uint32 the total allowable prints for this artwork
/// @param _metadataPath string the ipfs metadata path
/// @param _royaltyReceiver address the royalty receiver
/// @param _royaltyBps uint256 the royalty percentage in bps
function createArtwork(
address _creator,
uint32 _totalSupply,
string calldata _metadataPath,
address _royaltyReceiver,
uint256 _royaltyBps
) external returns (uint256);
/// @notice Update Artwork Royalty Info, can only be called by owner at emergency
/// @param _artworkId id of the artwork
/// @param _royaltyReceiver address the royalty receiver
/// @param _royaltyBps uint256 the royalty percentage in bps
function updateArtworkRoyaltyInfo(
uint256 _artworkId,
address _royaltyReceiver,
uint256 _royaltyBps
) external;
/// @notice Update Artwork metadata path (base uri), can only be called by owner at emergency
/// @param _artworkId id of the artwork
/// @param _metadataPath metadata path (base uri)
function updateArtworkMetadataPath(uint256 _artworkId, string memory _metadataPath) external;
/// @notice Increments the current print index of the artwork object, can be triggered by mint or burn.
/// @param _artworkId uint256 the id of the artwork
/// @param _increment uint32 the amount to increment by
function incrementArtworkPrintIndex(uint256 _artworkId, uint32 _increment) external;
/// Retrieves the artwork object by id
/// @param _artworkId uint256 the address of the creator
function getArtwork(uint256 _artworkId) external view returns (LibArtwork.Artwork memory artwork);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../lib/LibArtwork.sol";
/// @title Interface of TRLab NFT core contract
/// @author Joe
/// @notice This is the interface of TRLab NFT core contract
interface ITRLabCore {
/// @notice This event emits when a new NFT token has been minted.
/// @param id uint256 the id of the minted NFT token.
/// @param owner address the address of the token owner.
/// @param artworkId uint256 the id of the artwork of this token.
/// @param printEdition uint32 the print edition of this token.
/// @param tokenURI string the metadata ipfs URI.
event ArtworkReleaseCreated(
uint256 indexed id,
address indexed owner,
uint256 indexed artworkId,
uint32 printEdition,
string tokenURI
);
/// @notice This event emits when a batch of NFT tokens has been minted.
/// @param artworkId uint256 the id of the artwork of this token.
/// @param printEdition uint32 the new print edition of this artwork.
event ArtworkPrintIndexUpdated(uint256 indexed artworkId, uint32 indexed printEdition);
event NewArtworkStore(address indexed storeAddress);
/// @notice This event emits when an artwork has been burned.
/// @param artworkId uint256 the id of the burned artwork.
event ArtworkBurned(uint256 indexed artworkId);
/// @dev get current total supply of NFTs
function totalSupply() external view returns (uint256);
/// @dev sets the artwork store address.
/// @param _storeAddress address the address of the artwork store contract.
function setStoreAddress(address _storeAddress) external;
/// @dev set the royalty of a token. Can only be called by owner at emergency
/// @param _tokenId uint256 the id of the token
/// @param _receiver address the receiver address of the royalty
/// @param _bps uint256 the royalty percentage in bps
function setTokenRoyalty(
uint256 _tokenId,
address _receiver,
uint256 _bps
) external;
/// @dev set the royalty of tokens. Can only be called by owner at emergency
/// @param _tokenIds uint256[] the ids of the token
/// @param _receiver address the receiver address of the royalty
/// @param _bps uint256 the royalty percentage in bps
function setTokensRoyalty(
uint256[] calldata _tokenIds,
address _receiver,
uint256 _bps
) external;
/// @notice Retrieves the artwork object by id
/// @param _artworkId uint256 the address of the creator
/// @return artwork the artwork object
function getArtwork(uint256 _artworkId) external view returns (LibArtwork.Artwork memory artwork);
/// @notice Creates a new artwork object, artwork creator is _msgSender()
/// @param _totalSupply uint32 the total allowable prints for this artwork
/// @param _metadataPath string the ipfs metadata path
/// @param _royaltyReceiver address the royalty receiver
/// @param _royaltyBps uint256 the royalty percentage in bps
function createArtwork(
uint32 _totalSupply,
string calldata _metadataPath,
address _royaltyReceiver,
uint256 _royaltyBps
) external;
/// @notice Creates a new artwork object and mints it's first release token.
/// @dev No creations of any kind are allowed when the contract is paused.
/// @param _totalSupply uint32 the total allowable prints for this artwork
/// @param _metadataPath string the ipfs metadata path
/// @param _numReleases uint32 the number of tokens to be minted
/// @param _royaltyReceiver address the royalty receiver
/// @param _royaltyBps uint256 the royalty percentage in bps
function createArtworkAndReleases(
uint32 _totalSupply,
string calldata _metadataPath,
uint32 _numReleases,
address _royaltyReceiver,
uint256 _royaltyBps
) external;
/// @notice mints tokens of artwork.
/// @dev No creations of any kind are allowed when the contract is paused.
/// @param _artworkId uint256 the id of the artwork
/// @param _numReleases uint32 the number of tokens to be minted
function releaseArtwork(uint256 _artworkId, uint32 _numReleases) external;
/// @notice mints tokens of artwork in behave of receiver. Designed for buy-now contract.
/// @dev No creations of any kind are allowed when the contract is paused.
/// @param _receiver address the owner of the new nft token.
/// @param _artworkId uint256 the id of the artwork.
/// @param _numReleases uint32 the number of tokens to be minted.
function releaseArtworkForReceiver(
address _receiver,
uint256 _artworkId,
uint32 _numReleases
) external;
/// @notice get the next token id
/// @return the last token id
function getNextTokenId() external view returns (uint256);
/// @dev getter function for approvedTokenCreators mapping. Check if caller is approved creator.
/// @param caller address the address of caller to check.
/// @return true if caller is approved creator, otherwise false.
function approvedTokenCreators(address caller) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
import "../interfaces/IERC2981Upgradeable.sol";
contract ERC2981Upgradeable is Initializable, IERC2981Upgradeable, ERC165Upgradeable {
event RoyaltySet(uint256 indexed tokenId, Royalty royalty);
// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
struct Royalty {
address receiver;
uint256 bps;
}
// token id -> royalty
mapping(uint256 => Royalty) public royaltyMap;
function __ERC2981_init() internal initializer {
__ERC165_init_unchained();
__ERC2981_init_unchained();
}
function __ERC2981_init_unchained() internal initializer {}
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
Royalty memory royalty = royaltyMap[_tokenId];
receiver = royalty.receiver;
royaltyAmount = (_salePrice * royalty.bps) / 10000;
}
function _setRoyalty(uint256 _id, Royalty memory _royalty) internal {
// require(_royalty.account != address(0), "Recipient should be present");
require(_royalty.bps <= 10000, "Royalty bps should less than 10000");
royaltyMap[_id] = _royalty;
emit RoyaltySet(_id, _royalty);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* ERC165 bytes to add to interface array - set in parent contract
* implementing this standard
*
* bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
* bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
* _registerInterface(_INTERFACE_ID_ERC2981);
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC2981Upgradeable, ERC165Upgradeable)
returns (bool)
{
return
interfaceId == type(IERC2981Upgradeable).interfaceId ||
interfaceId == _INTERFACE_ID_ERC2981 ||
super.supportsInterface(interfaceId);
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library LibArtwork {
struct Artwork {
address creator;
uint32 printIndex;
uint32 totalSupply;
string metadataPath;
address royaltyReceiver;
uint256 royaltyBps; // royaltyBps is a value between 0 to 10000
}
struct ArtworkRelease {
// The unique edition number of this artwork release
uint32 printEdition;
// Reference ID to the artwork metadata
uint256 artworkId;
}
struct ArtworkOnSaleInfo {
address takeTokenAddress; // only accept erc20, should use WETH
uint256 takeAmount;
uint256 startTime; // timestamp in seconds
uint256 endTime;
uint256 purchaseLimit;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature(
"upgradeTo(address)",
oldImplementation
)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
AddressUpgradeable.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/*
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
///
/// @dev Interface for the NFT Royalty Standard
///
interface IERC2981Upgradeable is IERC165Upgradeable {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/// _registerInterface(_INTERFACE_ID_ERC2981);
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
/// @notice Informs callers that this contract supports ERC2981
/// @dev If `_registerInterface(_INTERFACE_ID_ERC2981)` is called
/// in the initializer, this should be automatic
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @return `true` if the contract implements
/// `_INTERFACE_ID_ERC2981` and `false` otherwise
function supportsInterface(bytes4 interfaceID) external view override returns (bool);
}
|
@inheritdoc ITRLabCore
|
function getArtwork(uint256 _artworkId) external view override returns (LibArtwork.Artwork memory artwork) {
artwork = _getArtwork(_artworkId);
}
| 1,574,244
|
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);
}
interface ITokensTypeStorage {
function isRegistred(address _address) external view returns(bool);
function getType(address _address) external view returns(bytes32);
function isPermittedAddress(address _address) external view returns(bool);
function owner() external view returns(address);
function addNewTokenType(address _token, string calldata _type) external;
function setTokenTypeAsOwner(address _token, string calldata _type) external;
}
interface UniswapFactoryInterface {
// Create Exchange
function createExchange(address token) external returns (address exchange);
// Get Exchange and Token Info
function getExchange(address token) external view returns (address exchange);
function getToken(address exchange) external view returns (address token);
function getTokenWithId(uint256 tokenId) external view returns (address token);
// Never use
function initializeFactory(address template) external;
}
interface UniswapExchangeInterface {
// Address of ERC20 token sold on this exchange
function tokenAddress() external view returns (address token);
// Address of Uniswap Factory
function factoryAddress() external view returns (address factory);
// Provide Liquidity
function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256);
function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256);
// Get Prices
function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
// Trade ETH to ERC20
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold);
// Trade ERC20 to ETH
function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought);
function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256 eth_bought);
function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold);
function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold);
// Trade ERC20 to ERC20
function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold);
// Trade ERC20 to Custom Pool
function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold);
function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold);
// ERC20 comaptibility for liquidity tokens
function name() external view returns(bytes32);
function symbol() external view returns(bytes32);
function decimals() external view returns(uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function allowance(address _owner, address _spender) external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function totalSupply() external view returns (uint256);
// Never use
function setup(address token_addr) external;
}
interface IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _depositAmount) external view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _sellAmount) external view returns (uint256);
function calculateCrossReserveReturn(uint256 _fromReserveBalance, uint32 _fromReserveRatio, uint256 _toReserveBalance, uint32 _toReserveRatio, uint256 _amount) external view returns (uint256);
function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) external view returns (uint256);
function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _totalRatio, uint256 _amount) external view returns (uint256);
}
interface IGetBancorAddressFromRegistry {
function getBancorContractAddresByName(string calldata _name) external view returns (address result);
}
interface IGetRatioForBancorAssets {
function getRatio(address _from, address _to, uint256 _amount) external view returns(uint256 result);
}
interface BancorConverterInterface {
function connectorTokens(uint index) external view returns(IERC20);
function fund(uint256 _amount) external;
function liquidate(uint256 _amount) external;
function getConnectorBalance(IERC20 _connectorToken) external view returns (uint256);
}
/*
* This contract allow buy/sell pool for Bancor and Uniswap assets
* and provide ratio and addition info for pool assets
*/
/**
* @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;
}
}
interface SmartTokenInterface is IERC20 {
function disableTransfers(bool _disable) external;
function issue(address _to, uint256 _amount) external;
function destroy(address _from, uint256 _amount) external;
function owner() external view returns (address);
}
contract PoolPortal {
using SafeMath for uint256;
IGetRatioForBancorAssets public bancorRatio;
IGetBancorAddressFromRegistry public bancorRegistry;
UniswapFactoryInterface public uniswapFactory;
address public BancorEtherToken;
// CoTrader platform recognize ETH by this address
IERC20 constant private ETH_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// Enum
// NOTE: You can add a new type at the end, but do not change this order
enum PortalType { Bancor, Uniswap }
// events
event BuyPool(address poolToken, uint256 amount, address trader);
event SellPool(address poolToken, uint256 amount, address trader);
// Contract for handle tokens types
ITokensTypeStorage public tokensTypes;
/**
* @dev contructor
*
* @param _bancorRegistryWrapper address of GetBancorAddressFromRegistry
* @param _bancorRatio address of GetRatioForBancorAssets
* @param _bancorEtherToken address of Bancor ETH wrapper
* @param _uniswapFactory address of Uniswap factory contract
* @param _tokensTypes address of the ITokensTypeStorage
*/
constructor(
address _bancorRegistryWrapper,
address _bancorRatio,
address _bancorEtherToken,
address _uniswapFactory,
address _tokensTypes
)
public
{
bancorRegistry = IGetBancorAddressFromRegistry(_bancorRegistryWrapper);
bancorRatio = IGetRatioForBancorAssets(_bancorRatio);
BancorEtherToken = _bancorEtherToken;
uniswapFactory = UniswapFactoryInterface(_uniswapFactory);
tokensTypes = ITokensTypeStorage(_tokensTypes);
}
/**
* @dev buy Bancor or Uniswap pool
*
* @param _amount amount of pool token
* @param _type pool type
* @param _poolToken pool token address
*/
function buyPool
(
uint256 _amount,
uint _type,
IERC20 _poolToken
)
external
payable
{
if(_type == uint(PortalType.Bancor)){
buyBancorPool(_poolToken, _amount);
}
else if (_type == uint(PortalType.Uniswap)){
require(_amount == msg.value, "Not enough ETH");
buyUniswapPool(address(_poolToken), _amount);
}
else{
// unknown portal type
revert();
}
emit BuyPool(address(_poolToken), _amount, msg.sender);
}
/**
* @dev helper for buy pool in Bancor network
*
* @param _poolToken address of bancor converter
* @param _amount amount of bancor relay
*/
function buyBancorPool(IERC20 _poolToken, uint256 _amount) private {
// get Bancor converter
address converterAddress = getBacorConverterAddressByRelay(address(_poolToken));
// calculate connectors amount for buy certain pool amount
(uint256 bancorAmount,
uint256 connectorAmount) = getBancorConnectorsAmountByRelayAmount(_amount, _poolToken);
// get converter as contract
BancorConverterInterface converter = BancorConverterInterface(converterAddress);
// approve bancor and coonector amount to converter
// get connectors
(IERC20 bancorConnector,
IERC20 ercConnector) = getBancorConnectorsByRelay(address(_poolToken));
// reset approve (some ERC20 not allow do new approve if already approved)
bancorConnector.approve(converterAddress, 0);
ercConnector.approve(converterAddress, 0);
// transfer from fund and approve to converter
_transferFromSenderAndApproveTo(bancorConnector, bancorAmount, converterAddress);
_transferFromSenderAndApproveTo(ercConnector, connectorAmount, converterAddress);
// buy relay from converter
converter.fund(_amount);
require(_amount > 0, "BNT pool recieved amount can not be zerro");
// transfer relay back to smart fund
_poolToken.transfer(msg.sender, _amount);
// transfer connectors back if a small amount remains
uint256 bancorRemains = bancorConnector.balanceOf(address(this));
if(bancorRemains > 0)
bancorConnector.transfer(msg.sender, bancorRemains);
uint256 ercRemains = ercConnector.balanceOf(address(this));
if(ercRemains > 0)
ercConnector.transfer(msg.sender, ercRemains);
setTokenType(address(_poolToken), "BANCOR_ASSET");
}
/**
* @dev helper for buy pool in Uniswap network
*
* @param _poolToken address of Uniswap exchange
* @param _ethAmount ETH amount (in wei)
*/
function buyUniswapPool(address _poolToken, uint256 _ethAmount)
private
returns(uint256 poolAmount)
{
// get token address
address tokenAddress = uniswapFactory.getToken(_poolToken);
// check if such a pool exist
if(tokenAddress != address(0x0000000000000000000000000000000000000000)){
// get tokens amd approve to exchange
uint256 erc20Amount = getUniswapTokenAmountByETH(tokenAddress, _ethAmount);
_transferFromSenderAndApproveTo(IERC20(tokenAddress), erc20Amount, _poolToken);
// get exchange contract
UniswapExchangeInterface exchange = UniswapExchangeInterface(_poolToken);
// set deadline
uint256 deadline = now + 15 minutes;
// buy pool
poolAmount = exchange.addLiquidity.value(_ethAmount)(
1,
erc20Amount,
deadline);
// reset approve (some ERC20 not allow do new approve if already approved)
IERC20(tokenAddress).approve(_poolToken, 0);
require(poolAmount > 0, "UNI pool recieved amount can not be zerro");
// transfer pool token back to smart fund
IERC20(_poolToken).transfer(msg.sender, poolAmount);
// transfer ERC20 remains
uint256 remainsERC = IERC20(tokenAddress).balanceOf(address(this));
if(remainsERC > 0)
IERC20(tokenAddress).transfer(msg.sender, remainsERC);
setTokenType(_poolToken, "UNISWAP_POOL");
}else{
// throw if such pool not Exist in Uniswap network
revert();
}
}
/**
* @dev return token amount by ETH input ratio
*
* @param _token address of ERC20 token
* @param _amount ETH amount (in wei)
*/
function getUniswapTokenAmountByETH(address _token, uint256 _amount)
public
view
returns(uint256)
{
UniswapExchangeInterface exchange = UniswapExchangeInterface(
uniswapFactory.getExchange(_token));
return exchange.getTokenToEthOutputPrice(_amount);
}
/**
* @dev sell Bancor or Uniswap pool
*
* @param _amount amount of pool token
* @param _type pool type
* @param _poolToken pool token address
*/
function sellPool
(
uint256 _amount,
uint _type,
IERC20 _poolToken
)
external
payable
{
if(_type == uint(PortalType.Bancor)){
sellPoolViaBancor(_poolToken, _amount);
}
else if (_type == uint(PortalType.Uniswap)){
sellPoolViaUniswap(_poolToken, _amount);
}
else{
// unknown portal type
revert();
}
emit SellPool(address(_poolToken), _amount, msg.sender);
}
/**
* @dev helper for sell pool in Bancor network
*
* @param _poolToken address of bancor relay
* @param _amount amount of bancor relay
*/
function sellPoolViaBancor(IERC20 _poolToken, uint256 _amount) private {
// transfer pool from fund
_poolToken.transferFrom(msg.sender, address(this), _amount);
// get Bancor Converter address
address converterAddress = getBacorConverterAddressByRelay(address(_poolToken));
// liquidate relay
BancorConverterInterface(converterAddress).liquidate(_amount);
// get connectors
(IERC20 bancorConnector,
IERC20 ercConnector) = getBancorConnectorsByRelay(address(_poolToken));
// transfer connectors back to fund
bancorConnector.transfer(msg.sender, bancorConnector.balanceOf(address(this)));
ercConnector.transfer(msg.sender, ercConnector.balanceOf(address(this)));
}
/**
* @dev helper for sell pool in Uniswap network
*
* @param _poolToken address of uniswap exchane
* @param _amount amount of uniswap pool
*/
function sellPoolViaUniswap(IERC20 _poolToken, uint256 _amount) private {
address tokenAddress = uniswapFactory.getToken(address(_poolToken));
// check if such a pool exist
if(tokenAddress != address(0x0000000000000000000000000000000000000000)){
UniswapExchangeInterface exchange = UniswapExchangeInterface(address(_poolToken));
// approve pool token
_transferFromSenderAndApproveTo(IERC20(_poolToken), _amount, address(_poolToken));
// get min returns
(uint256 minEthAmount,
uint256 minErcAmount) = getUniswapConnectorsAmountByPoolAmount(
_amount,
address(_poolToken));
// set deadline
uint256 deadline = now + 15 minutes;
// liquidate
(uint256 eth_amount,
uint256 token_amount) = exchange.removeLiquidity(
_amount,
minEthAmount,
minErcAmount,
deadline);
// transfer assets back to smart fund
msg.sender.transfer(eth_amount);
IERC20(tokenAddress).transfer(msg.sender, token_amount);
}else{
revert();
}
}
/**
* @dev helper for get bancor converter by bancor relay addrses
*
* @param _relay address of bancor relay
*/
function getBacorConverterAddressByRelay(address _relay)
public
view
returns(address converter)
{
converter = SmartTokenInterface(_relay).owner();
}
/**
* @dev helper for get Bancor ERC20 connectors addresses
*
* @param _relay address of bancor relay
*/
function getBancorConnectorsByRelay(address _relay)
public
view
returns(
IERC20 BNTConnector,
IERC20 ERCConnector
)
{
address converterAddress = getBacorConverterAddressByRelay(_relay);
BancorConverterInterface converter = BancorConverterInterface(converterAddress);
BNTConnector = converter.connectorTokens(0);
ERCConnector = converter.connectorTokens(1);
}
/**
* @dev return ERC20 address from Uniswap exchange address
*
* @param _exchange address of uniswap exchane
*/
function getTokenByUniswapExchange(address _exchange)
external
view
returns(address)
{
return uniswapFactory.getToken(_exchange);
}
/**
* @dev helper for get amounts for both Uniswap connectors for input amount of pool
*
* @param _amount relay amount
* @param _exchange address of uniswap exchane
*/
function getUniswapConnectorsAmountByPoolAmount(
uint256 _amount,
address _exchange
)
public
view
returns(uint256 ethAmount, uint256 ercAmount)
{
IERC20 token = IERC20(uniswapFactory.getToken(_exchange));
// total_liquidity exchange.totalSupply
uint256 totalLiquidity = UniswapExchangeInterface(_exchange).totalSupply();
// ethAmount = amount * exchane.eth.balance / total_liquidity
ethAmount = _amount.mul(_exchange.balance).div(totalLiquidity);
// ercAmount = amount * token.balanceOf(exchane) / total_liquidity
ercAmount = _amount.mul(token.balanceOf(_exchange)).div(totalLiquidity);
}
/**
* @dev helper for get amount for both Bancor connectors for input amount of pool
*
* @param _amount relay amount
* @param _relay address of bancor relay
*/
function getBancorConnectorsAmountByRelayAmount
(
uint256 _amount,
IERC20 _relay
)
public
view
returns(uint256 bancorAmount, uint256 connectorAmount)
{
// get converter contract
BancorConverterInterface converter = BancorConverterInterface(
SmartTokenInterface(address(_relay)).owner());
// calculate BNT and second connector amount
// get connectors
IERC20 bancorConnector = converter.connectorTokens(0);
IERC20 ercConnector = converter.connectorTokens(1);
// get connectors balance
uint256 bntBalance = converter.getConnectorBalance(bancorConnector);
uint256 ercBalance = converter.getConnectorBalance(ercConnector);
// get bancor formula contract
IBancorFormula bancorFormula = IBancorFormula(
bancorRegistry.getBancorContractAddresByName("BancorFormula"));
// calculate input
bancorAmount = bancorFormula.calculateFundCost(
_relay.totalSupply(),
bntBalance,
1000000,
_amount);
connectorAmount = bancorFormula.calculateFundCost(
_relay.totalSupply(),
ercBalance,
1000000,
_amount);
}
/**
* @dev helper for get ratio between assets in bancor newtork
*
* @param _from token or relay address
* @param _to token or relay address
* @param _amount amount from
*/
function getBancorRatio(address _from, address _to, uint256 _amount)
external
view
returns(uint256)
{
// Change ETH to Bancor ETH wrapper
address fromAddress = IERC20(_from) == ETH_TOKEN_ADDRESS ? BancorEtherToken : _from;
address toAddress = IERC20(_to) == ETH_TOKEN_ADDRESS ? BancorEtherToken : _to;
// return Bancor ratio
return bancorRatio.getRatio(fromAddress, toAddress, _amount);
}
/**
* @dev Transfers tokens to this contract and approves them to another address
*
* @param _source Token to transfer and approve
* @param _sourceAmount The amount to transfer and approve (in _source token)
* @param _to Address to approve to
*/
function _transferFromSenderAndApproveTo(IERC20 _source, uint256 _sourceAmount, address _to) private {
require(_source.transferFrom(msg.sender, address(this), _sourceAmount));
_source.approve(_to, _sourceAmount);
}
// Pool portal can mark each pool token as UNISWAP or BANCOR
function setTokenType(address _token, string memory _type) private {
// no need add type, if token alredy registred
if(tokensTypes.isRegistred(_token))
return;
tokensTypes.addNewTokenType(_token, _type);
}
// fallback payable function to receive ether from other contract addresses
fallback() external payable {}
}
|
helper for buy pool in Bancor network _poolToken address of bancor converter _amount amount of bancor relay/ get Bancor converter calculate connectors amount for buy certain pool amount get converter as contract approve bancor and coonector amount to converter get connectors reset approve (some ERC20 not allow do new approve if already approved) transfer from fund and approve to converter buy relay from converter transfer relay back to smart fund transfer connectors back if a small amount remains
|
function buyBancorPool(IERC20 _poolToken, uint256 _amount) private {
address converterAddress = getBacorConverterAddressByRelay(address(_poolToken));
(uint256 bancorAmount,
uint256 connectorAmount) = getBancorConnectorsAmountByRelayAmount(_amount, _poolToken);
BancorConverterInterface converter = BancorConverterInterface(converterAddress);
(IERC20 bancorConnector,
IERC20 ercConnector) = getBancorConnectorsByRelay(address(_poolToken));
bancorConnector.approve(converterAddress, 0);
ercConnector.approve(converterAddress, 0);
_transferFromSenderAndApproveTo(bancorConnector, bancorAmount, converterAddress);
_transferFromSenderAndApproveTo(ercConnector, connectorAmount, converterAddress);
converter.fund(_amount);
require(_amount > 0, "BNT pool recieved amount can not be zerro");
_poolToken.transfer(msg.sender, _amount);
uint256 bancorRemains = bancorConnector.balanceOf(address(this));
if(bancorRemains > 0)
bancorConnector.transfer(msg.sender, bancorRemains);
uint256 ercRemains = ercConnector.balanceOf(address(this));
if(ercRemains > 0)
ercConnector.transfer(msg.sender, ercRemains);
setTokenType(address(_poolToken), "BANCOR_ASSET");
}
| 14,713,694
|
./partial_match/1/0x3FC9b031aAF1E9F993CdD637833948B16828dB5D/sources/src/SchwapMarket.sol
|
There is a chance that pay_amt is smaller than 1 wei of the other token
|
function sellAllAmount(IERC20 pay_gem, uint pay_amt, IERC20 buy_gem, uint min_fill_amount)
public
returns (uint fill_amt)
{
require(!locked, "Reentrancy attempt");
uint offerId;
if (pay_amt * 1 ether < wdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) {
}
uint256 baux = rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9;
}
| 3,963,710
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/// @title Dividend-Paying Token Optional Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev OPTIONAL functions for a dividend-paying token contract.
interface DividendPayingTokenOptionalInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
}
/// @title Dividend-Paying Token Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev An interface for a dividend-paying token contract.
interface DividendPayingTokenInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract 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 () public {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
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;
}
}
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
*
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface 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;
}
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
/// @title Dividend-Paying Token
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether
/// to token holders as dividends and allows token holders to withdraw their dividends.
/// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
uint256 public totalDividendsDistributed;
constructor(string memory _name, string memory _symbol) public ERC20(_name, _symbol) {
}
/// @dev Distributes dividends whenever ether is paid to this contract.
receive() external payable {
distributeDividends();
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(msg.sender);
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
(bool success,) = user.call{value: _withdrawableDividend, gas: 3000}("");
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
contract KROO is ERC20 {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
KROODividendTracker public dividendTracker;
address public liquidityWallet;
uint256 public swapTokensAtAmount = 50000 * (10**18);
uint256 public maxSellTransactionAmount = 2000000 * (10**18);
uint256 public immutable ETHRewardsFee;
uint256 public immutable liquidityFee;
uint256 public immutable totalFees;
// sells have fees of 12 and 6 (10 * 1.2 and 5 * 1.2)
uint256 public sellFeeIncreaseFactor = 120;
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event ExcludeMultipleAccountsFromFees(address[] accounts, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SendDividends(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
constructor() public ERC20("Kroo Nation", "KROO") {
uint256 _ETHRewardsFee = 3;
uint256 _liquidityFee = 3;
ETHRewardsFee = _ETHRewardsFee;
liquidityFee = _liquidityFee;
totalFees = _ETHRewardsFee.add(_liquidityFee);
dividendTracker = new KROODividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
// exclude from paying fees or having max transaction amount
excludeFromFees(liquidityWallet, true);
excludeFromFees(address(this), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 23000000 * (10**18));
}
receive() external payable {
}
function updateDividendTracker(address newAddress) public onlyOwner {
require(newAddress != address(dividendTracker), "The dividend tracker already has that address");
KROODividendTracker newDividendTracker = KROODividendTracker(payable(newAddress));
require(newDividendTracker.owner() == address(this), "The new dividend tracker must be owned by the KROO token contract");
newDividendTracker.excludeFromDividends(address(newDividendTracker));
newDividendTracker.excludeFromDividends(address(this));
newDividendTracker.excludeFromDividends(owner());
newDividendTracker.excludeFromDividends(address(uniswapV2Router));
emit UpdateDividendTracker(newAddress, address(dividendTracker));
dividendTracker = newDividendTracker;
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
require(_isExcludedFromFees[account] != excluded, "KROO: Account is already the value of 'excluded'");
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function excludeFromDividends(address account) external onlyOwner {
dividendTracker.excludeFromDividends(account);
}
function setSellFactor(uint256 newFactor) external onlyOwner {
sellFeeIncreaseFactor = newFactor;
}
function setSwapAtAmount(uint256 newAmount) external onlyOwner {
swapTokensAtAmount = newAmount * (10**18);
}
function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
_isExcludedFromFees[accounts[i]] = excluded;
}
emit ExcludeMultipleAccountsFromFees(accounts, excluded);
}
function changeMaxSellAmount(uint256 newAmount) external onlyOwner {
maxSellTransactionAmount = newAmount * (10**18);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The Uniswap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateLiquidityWallet(address newLiquidityWallet) public onlyOwner {
require(newLiquidityWallet != liquidityWallet, "KROO: The liquidity wallet is already this address");
excludeFromFees(newLiquidityWallet, true);
emit LiquidityWalletUpdated(newLiquidityWallet, liquidityWallet);
liquidityWallet = newLiquidityWallet;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function isExcludedFromDividends(address account) public view returns(bool) {
return dividendTracker.excludedFromDividends(account);
}
function withdrawableDividendOf(address account) public view returns(uint256) {
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function claim() external {
dividendTracker.processAccount(msg.sender, false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(
!swapping &&
automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair
from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max
!_isExcludedFromFees[to] && //no max for those excluded from fees
from != liquidityWallet
) {
require(amount <= maxSellTransactionAmount, "Sell transfer amount exceeds the maxSellTransactionAmount.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
!swapping &&
!automatedMarketMakerPairs[from] &&
from != liquidityWallet &&
to != liquidityWallet
) {
swapping = true;
uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees);
swapAndLiquify(swapTokens);
uint256 sellTokens = balanceOf(address(this));
swapAndSendDividends(sellTokens);
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if(takeFee) {
uint256 fees = amount.mul(totalFees).div(100);
// if sell, multiply by 1.2
if(automatedMarketMakerPairs[to]) {
fees = fees.mul(sellFeeIncreaseFactor).div(100);
}
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {}
}
function swapAndLiquify(uint256 tokens) private {
// split the contract balance into halves
uint256 half = tokens.div(2);
uint256 otherHalf = tokens.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
liquidityWallet,
block.timestamp
);
}
function swapAndSendDividends(uint256 tokens) private {
swapTokensForEth(tokens);
uint256 dividends = address(this).balance;
(bool success,) = address(dividendTracker).call{value: dividends}("");
if(success) {
emit SendDividends(tokens, dividends);
}
}
}
contract KROODividendTracker is DividendPayingToken {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public minimumTokenBalanceForDividends;
event ExcludeFromDividends(address indexed account);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() public DividendPayingToken("KROO_Dividend_Tracker", "KROO_Dividend_Tracker") {
claimWait = 3600;
minimumTokenBalanceForDividends = 10000 * (10**18);
}
function _transfer(address, address, uint256) internal override {
require(false, "KROO_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() public override {
require(false, "KROO_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main KROO contract.");
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludeFromDividends(account);
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 3600 && newClaimWait <= 86400, "KROO_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "KROO_Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if(index >= 0) {
if(uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
}
else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ?
tokenHoldersMap.keys.length.sub(lastProcessedIndex) :
0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ?
lastClaimTime.add(claimWait) :
0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ?
nextClaimTime.sub(block.timestamp) :
0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if(index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if(lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if(excludedFromDividends[account]) {
return;
}
if(newBalance >= minimumTokenBalanceForDividends) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
}
else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if(amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
|
Create a uniswap pair for this new token exclude from receiving dividends exclude from paying fees or having max transaction amount
|
constructor() public ERC20("Kroo Nation", "KROO") {
uint256 _ETHRewardsFee = 3;
uint256 _liquidityFee = 3;
ETHRewardsFee = _ETHRewardsFee;
liquidityFee = _liquidityFee;
totalFees = _ETHRewardsFee.add(_liquidityFee);
dividendTracker = new KROODividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
excludeFromFees(liquidityWallet, true);
excludeFromFees(address(this), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(owner(), 23000000 * (10**18));
| 1,579,808
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import './math/SafeMath.sol';
import './token/BEP20/IBEP20.sol';
import './token/BEP20/SafeBEP20.sol';
import './access/Ownable.sol';
interface IMigratorChef {
function migrate(IBEP20 token) external returns (IBEP20);
}
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once XTT is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of XTTs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accXttPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accXttPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. XTTs to distribute per block.
uint256 lastRewardBlock; // Last block number that XTTs distribution occurs.
uint256 accXttPerShare; // Accumulated XTTs per share, times 1e12. See below.
uint256 executeTimestamp; // Timestamp to execute adding pool
bool withUpdate;
bool executed;
}
struct PoolAllocPointInfo {
uint256 pid; // Pool id
uint256 allocPoint; // How many allocation points assigned to this pool. XTTs to distribute per block.
uint256 executeTimestamp; // Timestamp to execute adding pool
bool withUpdate;
bool executed;
}
// The XTT TOKEN!
IBEP20 public xtt;
// XTT tokens created per block.
uint256 public xttPerBlock;
// Bonus muliplier for early xtt makers.
uint256 public BONUS_MULTIPLIER = 1;
// Store new value and execute when the time comes
uint256 public NEW_BONUS_MULTIPLIER = 1;
uint256 public NEW_BONUS_MULTIPLIER_TIMESTAMP = 0;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
IMigratorChef public newMigrator;
uint256 public newMigratorExecuteTimestamp = 0;
// Info of each pool.
PoolInfo[] public poolInfo;
PoolInfo[] public waitingPoolInfo; // Pools are waiting to add
PoolAllocPointInfo[] public poolAllocPointInfo; // Pools are waiting to update allocPoint
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when XTT mining starts.
uint256 public startBlock;
uint256 public constant MIN_TIME_LOCK_PERIOD = 24 hours; // 1 days
uint256 public constant MAX_ARRAY_LENGTH = 100; // 100 elements
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);
event SetMigrator(address indexed user, IMigratorChef migrator);
event UpdateMultiplier(address indexed user, uint256 multiplierNumber);
constructor(
// We will use XTT instead of CakeToken
IBEP20 _xtt,
/*
Modified
We do not need this token
*/
// SyrupBar _syrup,
/*
End modified
*/
uint256 _xttPerBlock,
uint256 _startBlock
) public {
xtt = _xtt;
xttPerBlock = _xttPerBlock;
startBlock = _startBlock;
// staking pool
poolInfo.push(PoolInfo({
lpToken: _xtt,
allocPoint: 1000,
lastRewardBlock: startBlock,
accXttPerShare: 0,
executeTimestamp: block.timestamp,
withUpdate: false,
executed: true
}));
totalAllocPoint = 1000;
}
function updateMultiplier(uint256 multiplierNumber, uint256 executeTimestamp) external onlyOwner {
// Check the time
require(
executeTimestamp >= block.timestamp.add(MIN_TIME_LOCK_PERIOD),
"executeTimestamp cannot be sooner than MIN_TIME_LOCK_PERIOD"
);
if(NEW_BONUS_MULTIPLIER_TIMESTAMP > 0 && block.timestamp >= NEW_BONUS_MULTIPLIER_TIMESTAMP){
if(BONUS_MULTIPLIER != NEW_BONUS_MULTIPLIER){
BONUS_MULTIPLIER = NEW_BONUS_MULTIPLIER;
}
}
NEW_BONUS_MULTIPLIER = multiplierNumber;
NEW_BONUS_MULTIPLIER_TIMESTAMP = executeTimestamp;
emit UpdateMultiplier(msg.sender, multiplierNumber);
}
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, IBEP20 _lpToken, bool _withUpdate, uint256 _executeTimestamp) external onlyOwner {
require(
_executeTimestamp >= block.timestamp.add(MIN_TIME_LOCK_PERIOD),
"_executeTimestamp cannot be sooner than MIN_TIME_LOCK_PERIOD"
);
require(
waitingPoolInfo.length < MAX_ARRAY_LENGTH,
"Please call executeAddPools function to process adding previous pools before adding more pools"
);
waitingPoolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: 0,
accXttPerShare: 0,
executeTimestamp: _executeTimestamp,
withUpdate: _withUpdate,
executed: false
}));
}
// Add a new lp to the pool. Can only be called by the owner.
function executeAddPools() external onlyOwner {
uint256 length = waitingPoolInfo.length;
if(length > 0){
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = waitingPoolInfo[pid];
if(!pool.executed && pool.executeTimestamp <= block.timestamp){
if (pool.withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
poolInfo.push(PoolInfo({
lpToken: pool.lpToken,
allocPoint: pool.allocPoint,
lastRewardBlock: lastRewardBlock,
accXttPerShare: 0,
executeTimestamp: pool.executeTimestamp,
withUpdate: pool.withUpdate,
executed: true
}));
pool.executed = true;
updateStakingPool();
// Remove this item
removeWaitingPool(pid);
pid--;
length--;
}
}
}
}
function removeWaitingPool(uint index) internal onlyOwner {
if (index >= waitingPoolInfo.length) return;
for (uint i = index; i<waitingPoolInfo.length-1; i++){
waitingPoolInfo[i] = waitingPoolInfo[i+1];
}
waitingPoolInfo.pop();
//delete waitingPoolInfo[waitingPoolInfo.length-1];
}
// Update the given pool's XTT allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate, uint256 _executeTimestamp) external onlyOwner {
require(
_executeTimestamp >= block.timestamp.add(MIN_TIME_LOCK_PERIOD),
"_executeTimestamp cannot be sooner than MIN_TIME_LOCK_PERIOD"
);
require(
poolAllocPointInfo.length < MAX_ARRAY_LENGTH,
"Please call executeUpdateAllocPoint function to process previous data before updating more pools"
);
poolAllocPointInfo.push(PoolAllocPointInfo({
pid: _pid,
allocPoint: _allocPoint,
executeTimestamp: _executeTimestamp,
withUpdate: _withUpdate,
executed: false
}));
}
// Update the given pool's XTT allocation point. Can only be called by the owner.
function executeUpdateAllocPoint() external onlyOwner {
uint256 length = poolAllocPointInfo.length;
if(length > 0){
for (uint256 index = 0; index < length; ++index) {
PoolAllocPointInfo storage poolAllocPoint = poolAllocPointInfo[index];
if(!poolAllocPoint.executed && poolAllocPoint.executeTimestamp <= block.timestamp){
if (poolAllocPoint.withUpdate) {
massUpdatePools();
}else{
updatePool(poolAllocPoint.pid);
}
uint256 prevAllocPoint = poolInfo[poolAllocPoint.pid].allocPoint;
if (prevAllocPoint != poolAllocPoint.allocPoint) {
poolInfo[poolAllocPoint.pid].allocPoint = poolAllocPoint.allocPoint;
totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(poolAllocPoint.allocPoint);
updateStakingPool();
}
poolAllocPoint.executed = true;
// Remove this item
removeAllocPoint(index);
index--;
length--;
}
}
}
}
function removeAllocPoint(uint index) internal onlyOwner {
if (index >= poolAllocPointInfo.length) return;
for (uint i = index; i<poolAllocPointInfo.length-1; i++){
poolAllocPointInfo[i] = poolAllocPointInfo[i+1];
}
poolAllocPointInfo.pop();
//delete poolAllocPointInfo[poolAllocPointInfo.length-1];
}
function updateStakingPool() internal {
uint256 length = poolInfo.length;
uint256 points = 0;
for (uint256 pid = 1; pid < length; ++pid) {
points = points.add(poolInfo[pid].allocPoint);
}
if (points != 0) {
points = points.div(3);
totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points);
poolInfo[0].allocPoint = points;
}
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator, uint256 _executeTimestamp) external onlyOwner {
require(
_executeTimestamp >= block.timestamp.add(MIN_TIME_LOCK_PERIOD),
"_executeTimestamp cannot be sooner than MIN_TIME_LOCK_PERIOD"
);
newMigrator = _migrator;
newMigratorExecuteTimestamp = _executeTimestamp;
emit SetMigrator(msg.sender, _migrator);
}
// Execute Set the migrator contract. Can only be called by the owner.
function executeSetMigrator() external onlyOwner {
if(newMigratorExecuteTimestamp > 0 && newMigratorExecuteTimestamp <= block.timestamp){
migrator = newMigrator;
newMigratorExecuteTimestamp = 0;
emit SetMigrator(msg.sender, newMigrator);
}
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) external {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IBEP20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IBEP20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
// Check to update new value
if(NEW_BONUS_MULTIPLIER_TIMESTAMP > 0 && block.timestamp >= NEW_BONUS_MULTIPLIER_TIMESTAMP){
return _to.sub(_from).mul(NEW_BONUS_MULTIPLIER);
}
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
// View function to see pending XTTs on frontend.
function pendingCake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accXttPerShare = pool.accXttPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 cakeReward = multiplier.mul(xttPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accXttPerShare = accXttPerShare.add(cakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accXttPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 xttReward = multiplier.mul(xttPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
/*
Modified
Do not need to mint more tokens
*/
// cake.mint(devaddr, cakeReward.div(10));
// cake.mint(address(syrup), cakeReward);
/*
End modified
*/
pool.accXttPerShare = pool.accXttPerShare.add(xttReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for XTT allocation.
function deposit(uint256 _pid, uint256 _amount) external {
require (_pid != 0, 'deposit XTT by staking');
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accXttPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeXttTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accXttPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) external {
require (_pid != 0, 'withdraw XTT by unstaking');
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.accXttPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeXttTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accXttPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Stake XTT tokens to MasterChef
function enterStaking(uint256 _amount) external {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
updatePool(0);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accXttPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeXttTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accXttPerShare).div(1e12);
/*
Modified
Do not need to mint this token
*/
// syrup.mint(msg.sender, _amount);
/*
End modified
*/
emit Deposit(msg.sender, 0, _amount);
}
// Withdraw XTT tokens from STAKING.
function leaveStaking(uint256 _amount) external {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(0);
uint256 pending = user.amount.mul(pool.accXttPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeXttTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accXttPerShare).div(1e12);
/*
Modified
Do not need to burn this token
*/
// syrup.burn(msg.sender, _amount);
/*
End modified
*/
emit Withdraw(msg.sender, 0, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) external {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe xtt transfer function, just in case if rounding error causes pool to not have enough XTTs.
function safeXttTransfer(address _to, uint256 _amount) internal {
xtt.safeTransfer(_to, _amount);
}
}
|
Add a new lp to the pool. Can only be called by the owner.
|
function executeAddPools() external onlyOwner {
uint256 length = waitingPoolInfo.length;
if(length > 0){
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = waitingPoolInfo[pid];
if(!pool.executed && pool.executeTimestamp <= block.timestamp){
if (pool.withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
poolInfo.push(PoolInfo({
lpToken: pool.lpToken,
allocPoint: pool.allocPoint,
lastRewardBlock: lastRewardBlock,
accXttPerShare: 0,
executeTimestamp: pool.executeTimestamp,
withUpdate: pool.withUpdate,
executed: true
}));
pool.executed = true;
updateStakingPool();
pid--;
length--;
}
}
}
}
| 990,738
|
pragma solidity ^0.4.23;
/// @title ERC-165 Standard Interface Detection
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
interface ERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
contract ERC721 is ERC165 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) external view returns (uint256);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function approve(address _approved, uint256 _tokenId) external;
function setApprovalForAll(address _operator, bool _approved) external;
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard
interface ERC721TokenReceiver {
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
contract AccessAdmin {
bool public isPaused = false;
address public addrAdmin;
event AdminTransferred(address indexed preAdmin, address indexed newAdmin);
constructor() public {
addrAdmin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == addrAdmin);
_;
}
modifier whenNotPaused() {
require(!isPaused);
_;
}
modifier whenPaused {
require(isPaused);
_;
}
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0));
emit AdminTransferred(addrAdmin, _newAdmin);
addrAdmin = _newAdmin;
}
function doPause() external onlyAdmin whenNotPaused {
isPaused = true;
}
function doUnpause() external onlyAdmin whenPaused {
isPaused = false;
}
}
//Ether League Hero Token
contract ELHeroToken is ERC721,AccessAdmin{
struct Card {
uint16 protoId; // 0 10001-10025 Gen 0 Heroes
uint16 hero; // 1 1-25 hero ID
uint16 quality; // 2 rarities: 1 Common 2 Uncommon 3 Rare 4 Epic 5 Legendary 6 Gen 0 Heroes
uint16 feature; // 3 feature
uint16 level; // 4 level
uint16 attrExt1; // 5 future stat 1
uint16 attrExt2; // 6 future stat 2
}
/// @dev All card tokenArray (not exceeding 2^32-1)
Card[] public cardArray;
/// @dev Amount of tokens destroyed
uint256 destroyCardCount;
/// @dev Card token ID vs owner address
mapping (uint256 => address) cardIdToOwner;
/// @dev cards owner by the owner (array)
mapping (address => uint256[]) ownerToCardArray;
/// @dev card token ID search in owner array
mapping (uint256 => uint256) cardIdToOwnerIndex;
/// @dev The authorized address for each token
mapping (uint256 => address) cardIdToApprovals;
/// @dev The authorized operators for each address
mapping (address => mapping (address => bool)) operatorToApprovals;
/// @dev Trust contract
mapping (address => bool) actionContracts;
function setActionContract(address _actionAddr, bool _useful) external onlyAdmin {
actionContracts[_actionAddr] = _useful;
}
function getActionContract(address _actionAddr) external view onlyAdmin returns(bool) {
return actionContracts[_actionAddr];
}
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event CreateCard(address indexed owner, uint256 tokenId, uint16 protoId, uint16 hero, uint16 quality, uint16 createType);
event DeleteCard(address indexed owner, uint256 tokenId, uint16 deleteType);
event ChangeCard(address indexed owner, uint256 tokenId, uint16 changeType);
modifier isValidToken(uint256 _tokenId) {
require(_tokenId >= 1 && _tokenId <= cardArray.length);
require(cardIdToOwner[_tokenId] != address(0));
_;
}
modifier canTransfer(uint256 _tokenId) {
address owner = cardIdToOwner[_tokenId];
require(msg.sender == owner || msg.sender == cardIdToApprovals[_tokenId] || operatorToApprovals[owner][msg.sender]);
_;
}
// ERC721
function supportsInterface(bytes4 _interfaceId) external view returns(bool) {
// ERC165 || ERC721 || ERC165^ERC721
return (_interfaceId == 0x01ffc9a7 || _interfaceId == 0x80ac58cd || _interfaceId == 0x8153916a) && (_interfaceId != 0xffffffff);
}
constructor() public {
addrAdmin = msg.sender;
cardArray.length += 1;
}
function name() public pure returns(string) {
return "Ether League Hero Token";
}
function symbol() public pure returns(string) {
return "ELHT";
}
/// @dev Search for token quantity address
/// @param _owner Address that needs to be searched
/// @return Returns token quantity
function balanceOf(address _owner) external view returns (uint256){
require(_owner != address(0));
return ownerToCardArray[_owner].length;
}
/// @dev Find the owner of an ELHT
/// @param _tokenId The tokenId of ELHT
/// @return Give The address of the owner of this ELHT
function ownerOf(uint256 _tokenId) external view returns (address){
return cardIdToOwner[_tokenId];
}
/// @dev Transfers the ownership of an ELHT from one address to another address
/// @param _from The current owner of the ELHT
/// @param _to The new owner
/// @param _tokenId The ELHT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external whenNotPaused{
_safeTransferFrom(_from, _to, _tokenId, data);
}
/// @dev Transfers the ownership of an ELHT from one address to another address
/// @param _from The current owner of the ELHT
/// @param _to The new owner
/// @param _tokenId The ELHT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/// @dev Transfer ownership of an ELHT, '_to' must be a vaild address, or the ELHT will lost
/// @param _from The current owner of the ELHT
/// @param _to The new owner
/// @param _tokenId The ELHT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused isValidToken(_tokenId) canTransfer(_tokenId){
address owner = cardIdToOwner[_tokenId];
require(owner != address(0));
require(_to != address(0));
require(owner == _from);
_transfer(_from, _to, _tokenId);
}
/// @dev Set or reaffirm the approved address for an ELHT
/// @param _approved The new approved ELHT controller
/// @param _tokenId The ELHT to approve
function approve(address _approved, uint256 _tokenId) external whenNotPaused{
address owner = cardIdToOwner[_tokenId];
require(owner != address(0));
require(msg.sender == owner || operatorToApprovals[owner][msg.sender]);
cardIdToApprovals[_tokenId] = _approved;
emit Approval(owner, _approved, _tokenId);
}
/// @dev Enable or disable approval for a third party ("operator") to manage all your asset.
/// @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 whenNotPaused{
operatorToApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @dev Get the approved address for a single ELHT
/// @param _tokenId The ELHT to find the approved address for
/// @return The approved address for this ELHT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view isValidToken(_tokenId) returns (address) {
return cardIdToApprovals[_tokenId];
}
/// @dev Query if an address is an authorized operator for another address ๆฅ่ฏขๅฐๅๆฏๅฆไธบๅฆไธๅฐๅ็ๆๆๆไฝ่
/// @param _owner The address that owns the ELHTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return operatorToApprovals[_owner][_operator];
}
/// @dev Count ELHTs tracked by this contract
/// @return A count of valid ELHTs tracked by this contract, where each one of them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256) {
return cardArray.length - destroyCardCount - 1;
}
/// @dev Actually perform the safeTransferFrom
function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) internal isValidToken(_tokenId) canTransfer(_tokenId){
address owner = cardIdToOwner[_tokenId];
require(owner != address(0));
require(_to != address(0));
require(owner == _from);
_transfer(_from, _to, _tokenId);
// Do the callback after everything is done to avoid reentrancy attack
uint256 codeSize;
assembly { codeSize := extcodesize(_to) }
if (codeSize == 0) {
return;
}
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data);
// bytes4(keccak256("onERC721Received(address,uint256,bytes)")) = 0xf0b9e5ba;
require(retval == 0xf0b9e5ba);
}
/// @dev Do the real transfer with out any condition checking
/// @param _from The old owner of this ELHT(If created: 0x0)
/// @param _to The new owner of this ELHT
/// @param _tokenId The tokenId of the ELHT
function _transfer(address _from, address _to, uint256 _tokenId) internal {
if (_from != address(0)) {
uint256 indexFrom = cardIdToOwnerIndex[_tokenId];
uint256[] storage cdArray = ownerToCardArray[_from];
require(cdArray[indexFrom] == _tokenId);
// If the ELHT is not the element of array, change it to with the last
if (indexFrom != cdArray.length - 1) {
uint256 lastTokenId = cdArray[cdArray.length - 1];
cdArray[indexFrom] = lastTokenId;
cardIdToOwnerIndex[lastTokenId] = indexFrom;
}
cdArray.length -= 1;
if (cardIdToApprovals[_tokenId] != address(0)) {
delete cardIdToApprovals[_tokenId];
}
}
// Give the ELHT to '_to'
cardIdToOwner[_tokenId] = _to;
ownerToCardArray[_to].push(_tokenId);
cardIdToOwnerIndex[_tokenId] = ownerToCardArray[_to].length - 1;
emit Transfer(_from != address(0) ? _from : this, _to, _tokenId);
}
/*----------------------------------------------------------------------------------------------------------*/
/// @dev Card creation
/// @param _owner Owner of the equipment created
/// @param _attrs Attributes of the equipment created
/// @return Token ID of the equipment created
function createCard(address _owner, uint16[5] _attrs, uint16 _createType) external whenNotPaused returns(uint256){
require(actionContracts[msg.sender]);
require(_owner != address(0));
uint256 newCardId = cardArray.length;
require(newCardId < 4294967296);
cardArray.length += 1;
Card storage cd = cardArray[newCardId];
cd.protoId = _attrs[0];
cd.hero = _attrs[1];
cd.quality = _attrs[2];
cd.feature = _attrs[3];
cd.level = _attrs[4];
_transfer(0, _owner, newCardId);
emit CreateCard(_owner, newCardId, _attrs[0], _attrs[1], _attrs[2], _createType);
return newCardId;
}
/// @dev One specific attribute of the equipment modified
function _changeAttrByIndex(Card storage _cd, uint16 _index, uint16 _val) internal {
if (_index == 2) {
_cd.quality = _val;
} else if(_index == 3) {
_cd.feature = _val;
} else if(_index == 4) {
_cd.level = _val;
} else if(_index == 5) {
_cd.attrExt1 = _val;
} else if(_index == 6) {
_cd.attrExt2 = _val;
}
}
/// @dev Equiment attributes modified (max 4 stats modified)
/// @param _tokenId Equipment Token ID
/// @param _idxArray Stats order that must be modified
/// @param _params Stat value that must be modified
/// @param _changeType Modification type such as enhance, socket, etc.
function changeCardAttr(uint256 _tokenId, uint16[5] _idxArray, uint16[5] _params, uint16 _changeType) external whenNotPaused isValidToken(_tokenId) {
require(actionContracts[msg.sender]);
Card storage cd = cardArray[_tokenId];
if (_idxArray[0] > 0) _changeAttrByIndex(cd, _idxArray[0], _params[0]);
if (_idxArray[1] > 0) _changeAttrByIndex(cd, _idxArray[1], _params[1]);
if (_idxArray[2] > 0) _changeAttrByIndex(cd, _idxArray[2], _params[2]);
if (_idxArray[3] > 0) _changeAttrByIndex(cd, _idxArray[3], _params[3]);
if (_idxArray[4] > 0) _changeAttrByIndex(cd, _idxArray[4], _params[4]);
emit ChangeCard(cardIdToOwner[_tokenId], _tokenId, _changeType);
}
/// @dev Equipment destruction
/// @param _tokenId Equipment Token ID
/// @param _deleteType Destruction type, such as craft
function destroyCard(uint256 _tokenId, uint16 _deleteType) external whenNotPaused isValidToken(_tokenId) {
require(actionContracts[msg.sender]);
address _from = cardIdToOwner[_tokenId];
uint256 indexFrom = cardIdToOwnerIndex[_tokenId];
uint256[] storage cdArray = ownerToCardArray[_from];
require(cdArray[indexFrom] == _tokenId);
if (indexFrom != cdArray.length - 1) {
uint256 lastTokenId = cdArray[cdArray.length - 1];
cdArray[indexFrom] = lastTokenId;
cardIdToOwnerIndex[lastTokenId] = indexFrom;
}
cdArray.length -= 1;
cardIdToOwner[_tokenId] = address(0);
delete cardIdToOwnerIndex[_tokenId];
destroyCardCount += 1;
emit Transfer(_from, 0, _tokenId);
emit DeleteCard(_from, _tokenId, _deleteType);
}
/// @dev Safe transfer by trust contracts
function safeTransferByContract(uint256 _tokenId, address _to) external whenNotPaused{
require(actionContracts[msg.sender]);
require(_tokenId >= 1 && _tokenId <= cardArray.length);
address owner = cardIdToOwner[_tokenId];
require(owner != address(0));
require(_to != address(0));
require(owner != _to);
_transfer(owner, _to, _tokenId);
}
/// @dev Get fashion attrs by tokenId
function getCard(uint256 _tokenId) external view isValidToken(_tokenId) returns (uint16[7] datas) {
Card storage cd = cardArray[_tokenId];
datas[0] = cd.protoId;
datas[1] = cd.hero;
datas[2] = cd.quality;
datas[3] = cd.feature;
datas[4] = cd.level;
datas[5] = cd.attrExt1;
datas[6] = cd.attrExt2;
}
/// Get tokenIds and flags by owner
function getOwnCard(address _owner) external view returns(uint256[] tokens, uint32[] flags) {
require(_owner != address(0));
uint256[] storage cdArray = ownerToCardArray[_owner];
uint256 length = cdArray.length;
tokens = new uint256[](length);
flags = new uint32[](length);
for (uint256 i = 0; i < length; ++i) {
tokens[i] = cdArray[i];
Card storage cd = cardArray[cdArray[i]];
flags[i] = uint32(uint32(cd.protoId) * 1000 + uint32(cd.hero) * 10 + cd.quality);
}
}
/// ELHT token info returned based on Token ID transfered (64 at most)
function getCardAttrs(uint256[] _tokens) external view returns(uint16[] attrs) {
uint256 length = _tokens.length;
require(length <= 64);
attrs = new uint16[](length * 11);
uint256 tokenId;
uint256 index;
for (uint256 i = 0; i < length; ++i) {
tokenId = _tokens[i];
if (cardIdToOwner[tokenId] != address(0)) {
index = i * 11;
Card storage cd = cardArray[tokenId];
attrs[index] = cd.hero;
attrs[index + 1] = cd.quality;
attrs[index + 2] = cd.feature;
attrs[index + 3] = cd.level;
attrs[index + 4] = cd.attrExt1;
attrs[index + 5] = cd.attrExt2;
}
}
}
}
|
Enable or disable approval for a third party ("operator") to manage all your asset. _operator Address to add to the set of authorized operators. _approved True if the operators is approved, false to revoke approval
|
function setApprovalForAll(address _operator, bool _approved) external whenNotPaused{
operatorToApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
| 2,483,225
|
//SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.7.0 <0.9.0;
import "./Whitelist.sol";
import "./Admin.sol";
import "./ReceiverFactory.sol";
/*
This class is a factory class used to produce instances of Corporates, Corporates will act as a parent class to Subsidiary
*/
contract CorporateFactory {
address public owner; // owner address
Admin public admin; // admin contract
mapping(uint => corporate) public corporates; //list of corporates
uint public numCorps; // number of corporates
bool active = true; //whether this contract is active
// Struct used to store corporates in the mapping
struct corporate {
address corpAddress;
uint id;
bool valid;
}
// The constructor links an associated Admin contract
constructor(Admin admin_) {
owner = msg.sender;
admin = admin_;
}
//function to create a new Corporate with name <corpName>
function createCorp(string memory corpName, address owner_) public permissioned activeContract returns(address corpAddr){
Corporate newCorp = new Corporate(admin,corpName, owner_, numCorps); // passes parent's admin, address of owner and corp name
corporates[numCorps] = corporate(address(newCorp), numCorps, true); // add the corporate to the last spot in the list
numCorps += 1;
return address(newCorp);
}
// get corporate address given id
function getCorporate(uint id) public view activeContract returns(address) {
return corporates[id].corpAddress;
}
// This function is used by the Admin to activate/disable the Corporate Factory contracts
function toggleContractActivation() public adminOnly returns (bool){
active = !active;
return(active);
}
// This function is used to mark a corporate as invalid
function disableCorporate(uint id) public permissioned activeContract{
require(checkIfCorporateValid(id) == true); // check that it is still valid
Corporate(corporates[id].corpAddress).disableCorporate(); // disable the Corporate
}
function checkIfCorporateValid(uint id) public view activeContract returns (bool){
require(corporates[id].corpAddress != address(0), 'Not a listed corporate'); //check if corporate in factory list
return Corporate(corporates[id].corpAddress).valid(); // return if the contract is valid
}
modifier adminOnly {
require(msg.sender == admin.owner(), "Only the admin can access this function");
_;
}
modifier permissioned {
require(msg.sender == owner || msg.sender == admin.owner(), "Only the owner/admin can access this function");
_;
}
modifier activeContract{
require(active == true, "Contract no longer active");
_;
}
}
contract Corporate {
address public owner; // owner of the contract e.g. a Corporates own address
Admin public admin; // admin of the system
CorporateFactory parent; // Corporate Factory this was created from
uint public corporate_id; // Corporate ID assigned to
string public corporate_name_; // name of the Corporate
mapping(address => sub) public subsidiaries; // a mapping of addresses to the sub struct.
address[] public subs; // could make this into a struct so the id can be found easily.
Whitelist public whitelist; //whitelist associated with the corporate
bool public valid; //checks if the contract is valid
uint public numOfSubs;
struct sub {
address subAddress;
uint id;
bool valid;
}
// allows for an owner i.e. corporate to be passed into the constructor
constructor(Admin admin_,string memory name, address owner_, uint corp_id_){
admin = admin_;
owner = owner_;
corporate_name_ = name;
corporate_id = corp_id_;
parent = CorporateFactory(msg.sender);
valid = true;
}
// This function is used to create a Subsidiary branch of the Corporate representing a store
function createSub() public permissioned validContract returns(address){
Subsidiary newSub = new Subsidiary(admin, owner);
subs.push(address(newSub)); // add new sub to subsidiary array
subsidiaries[address(newSub)] = sub(address(newSub), numOfSubs, true); // add new sub to mapping
numOfSubs++;
return address(newSub);
}
// Returns the subsidiary struct
function getSubContract(uint id) public view validContract returns(address) {
return subs[id];
}
function checkIfSubsidiaryValid(address toCheck) public view validContract returns(bool){
require(subsidiaries[toCheck].subAddress != address(0), "Not a subsidiary address");
return subsidiaries[toCheck].valid;
}
function disableContract() public permissioned validContract{
valid = false;
}
// Updates the whiteList
function updateWhitelist(Whitelist whitelist_) public permissioned validContract {
require(whitelist_.owner() == owner || whitelist.owner() == admin.owner(), "Whitelist not created by known party");
whitelist = whitelist_;
}
// Disable the Corporate
function disableCorporate() public permissioned validContract returns(bool){
valid = false;
return valid;
}
modifier adminOnly {
require(msg.sender == admin.owner(), "Only the admin can access this function");
_;
}
modifier permissioned {
require(msg.sender == owner || msg.sender == admin.owner() || msg.sender == address(parent), "Only the owner/admin/parent can access this function");
_;
}
modifier validContract {
require(valid == true);
_;
}
}
// This contract represents a Subsidiary branch of a Corporate partner
contract Subsidiary {
Corporate public parent_; // Corporate Contract
Admin public admin; //Admin
address public owner; //Corporate owner address
uint public amount; //Balance
mapping(address => bool) private permissionedAddress; //provides an array of addresses the Sub can withdraw funds to
event ValueReceived(address user, uint amount);
bool public valid;
// Transaction struct to be sent to the off-chain oracle
struct Transaction {
uint txId;
address receiverId;
uint txAmount;
string txLink;
}
// Event that logs the off-chain oracle call
event TransactionRequest (
uint txId,
address receiverId,
uint txAmount
);
// transaction id to person id
mapping(uint => Transaction) public transactions; // List of transactions @DEV: need to provide rec address and amount (maybe through struct)
uint public numOfTransactions;
constructor(Admin admin_, address owner_) {
parent_ = Corporate(msg.sender);
admin = admin_;
owner = owner_;
permissionedAddress[owner_] = true;
amount = address(this).balance;
valid = true;
}
// need to make sure no possibility for double spend
// Will reset to zero and prevent withdrawl whilst the send transaction is processed.
function getTake() public payable accountsAccess accountValid returns(bool) {
uint prevAmount = amount;
amount = 0;
return payable(address(parent_)).send(prevAmount);
}
// Oracle end point for inserting transaction details into blockchain and recording the mapping
// function insertTransaction(uint txId, address receiverId, uint txAmount) restricted accountValid public returns(bool) {
function insertTransaction(Receiver receiverId, uint txAmount, string memory link) public returns(bool) {
transactions[numOfTransactions] = Transaction(numOfTransactions, address(receiverId), txAmount, link);
numOfTransactions++;
require(receiverId.admin().owner() == admin.owner(), "This receiver is not created by admin");
receiverId.sendSubFunds(this, txAmount);
return true;
}
// Provides functionality to receive funds for the subsidiary
receive() external accountValid payable{
amount = address(this).balance;
}
modifier restricted {
require(msg.sender == address(parent_) || permissionedAddress[msg.sender] == true);
_;
}
// Restrict account access
modifier accountsAccess {
require(msg.sender == address(parent_));
_;
}
modifier accountValid {
require(valid == true, "This Subsidiary is no longer valid");
_;
}
}
|
Oracle end point for inserting transaction details into blockchain and recording the mapping function insertTransaction(uint txId, address receiverId, uint txAmount) restricted accountValid public returns(bool) {
|
function insertTransaction(Receiver receiverId, uint txAmount, string memory link) public returns(bool) {
transactions[numOfTransactions] = Transaction(numOfTransactions, address(receiverId), txAmount, link);
numOfTransactions++;
require(receiverId.admin().owner() == admin.owner(), "This receiver is not created by admin");
receiverId.sendSubFunds(this, txAmount);
return true;
}
| 15,839,221
|
./full_match/5/0x6ac1074235eF587f047fd44DFe9977788A54a1FF/sources/contracts/Strategy/NoopStrategy.sol
|
Cashes everything out and withdraws to the vault/
|
function withdrawAllToVault() external override onlyVault {
withdrawAllCalled = true;
if (underlyingERC.balanceOf(address(this)) > 0) {
underlyingERC.safeTransfer(
vault,
underlyingERC.balanceOf(address(this))
);
}
}
| 1,899,140
|
/**
*Submitted for verification at Etherscan.io on 2021-12-01
*/
/**
DeepDefiCapital.com
t.me/DeepDefiCapital
https://twitter.com/DeepDefiCapital
https://medium.com/@deepdeficapital/deep-defi-capital-634bffd1299c
Deep Defi Capital is an alternative investment firm with a key focus in decentralised investments.
By operating within the defi space, all investors can partake within the protocol with anonymity,
flexibility and accessibility.
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface 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;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract DeepDefiCapital is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'DeepDefiCapital';
string private _symbol = 'DDC';
uint8 private _decimals = 9;
uint256 private _taxFee = 10;
uint256 private _teamFee = 10;
uint256 private _previousTaxFee = _taxFee;
uint256 private _previousTeamFee = _teamFee;
address payable public _PrincipalProtectionWalletAddress;
address payable public _YieldFarmingWalletAddress;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwap = false;
bool public swapEnabled = true;
uint256 private _maxTxAmount = 1000000000000 * 10**9;
uint256 private _numOfTokensToExchangeForTeam = 5 * 10**3 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor (address payable PrincipalProtectionWalletAddress, address payable YieldFarmingWalletAddress) public {
_PrincipalProtectionWalletAddress = PrincipalProtectionWalletAddress;
_YieldFarmingWalletAddress = YieldFarmingWalletAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // UniswapV2 for Ethereum network
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcluded(address account) public view returns (bool) {
return _isExcluded[account];
}
function setExcludeFromFee(address account, bool excluded) external onlyOwner() {
_isExcludedFromFee[account] = excluded;
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeAccount(address account) external onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeAccount(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function removeAllFee() private {
if(_taxFee == 0 && _teamFee == 0) return;
_previousTaxFee = _taxFee;
_previousTeamFee = _teamFee;
_taxFee = 0;
_teamFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_teamFee = _previousTeamFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if(sender != owner() && recipient != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam;
if (!inSwap && swapEnabled && overMinTokenBalance && sender != uniswapV2Pair) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
sendETHToTeam(address(this).balance);
}
}
bool takeFee = true;
if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){
takeFee = false;
}
_tokenTransfer(sender,recipient,amount,takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToTeam(uint256 amount) private {
_PrincipalProtectionWalletAddress.transfer(amount.div(2));
_YieldFarmingWalletAddress.transfer(amount.div(2));
}
function manualSwap() external onlyOwner() {
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualSend() external onlyOwner() {
uint256 contractETHBalance = address(this).balance;
sendETHToTeam(contractETHBalance);
}
function setSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _taxFee, _teamFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(uint256 tAmount, uint256 taxFee, uint256 teamFee) private pure returns (uint256, uint256, uint256) {
uint256 tFee = tAmount.mul(taxFee).div(100);
uint256 tTeam = tAmount.mul(teamFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getTaxFee() private view returns(uint256) {
return _taxFee;
}
function _getMaxTxAmount() private view returns(uint256) {
return _maxTxAmount;
}
function _getETHBalance() public view returns(uint256 balance) {
return address(this).balance;
}
function _setTaxFee(uint256 taxFee) external onlyOwner() {
require(taxFee >= 1 && taxFee <= 25, 'taxFee should be in 1 - 25');
_taxFee = taxFee;
}
function _setTeamFee(uint256 teamFee) external onlyOwner() {
require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25');
_teamFee = teamFee;
}
function BridgingSetMaxTx(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount <= 1000000000000 * 10**9, 'maxTxAmount should be greater than 100000000000000e9');
_maxTxAmount = maxTxAmount;
}
}
|
solhint-disable-next-line avoid-low-level-calls, avoid-call-value
|
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
require(success, "Address: unable to send value, recipient may have reverted");
}
| 10,666,943
|
// File: @openzeppelin/contracts-ethereum-package/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-ethereum-package/contracts/drafts/SignedSafeMath.sol
pragma solidity ^0.5.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;
}
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// 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-ethereum-package/contracts/ownership/Ownable.sol
pragma solidity ^0.5.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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(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;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/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-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/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: @0x/contracts-utils/contracts/src/LibEIP712.sol
/*
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.9;
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct)
internal
pure
returns (bytes32 result)
{
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// File: @0x/contracts-exchange-libs/contracts/src/LibOrder.sol
/*
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.9;
library LibOrder {
using LibOrder for Order;
// Hash for the EIP712 Order Schema:
// keccak256(abi.encodePacked(
// "Order(",
// "address makerAddress,",
// "address takerAddress,",
// "address feeRecipientAddress,",
// "address senderAddress,",
// "uint256 makerAssetAmount,",
// "uint256 takerAssetAmount,",
// "uint256 makerFee,",
// "uint256 takerFee,",
// "uint256 expirationTimeSeconds,",
// "uint256 salt,",
// "bytes makerAssetData,",
// "bytes takerAssetData,",
// "bytes makerFeeAssetData,",
// "bytes takerFeeAssetData",
// ")"
// ))
bytes32 constant internal _EIP712_ORDER_SCHEMA_HASH =
0xf80322eb8376aafb64eadf8f0d7623f22130fd9491a221e902b713cb984a7534;
// A valid order remains fillable until it is expired, fully filled, or cancelled.
// An order's status is unaffected by external factors, like account balances.
enum OrderStatus {
INVALID, // Default value
INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount
INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount
FILLABLE, // Order is fillable
EXPIRED, // Order has already expired
FULLY_FILLED, // Order is fully filled
CANCELLED // Order has been cancelled
}
// solhint-disable max-line-length
/// @dev Canonical order structure.
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled.
uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy.
bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy.
bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy.
}
// solhint-enable max-line-length
/// @dev Order information returned by `getOrderInfo()`.
struct OrderInfo {
OrderStatus orderStatus; // Status that describes order's validity and fillability.
bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash).
uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled.
}
/// @dev Calculates the EIP712 typed data hash of an order with a given domain separator.
/// @param order The order structure.
/// @return EIP712 typed data hash of the order.
function getTypedDataHash(Order memory order, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 orderHash)
{
orderHash = LibEIP712.hashEIP712Message(
eip712ExchangeDomainHash,
order.getStructHash()
);
return orderHash;
}
/// @dev Calculates EIP712 hash of the order struct.
/// @param order The order structure.
/// @return EIP712 hash of the order struct.
function getStructHash(Order memory order)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_ORDER_SCHEMA_HASH;
bytes memory makerAssetData = order.makerAssetData;
bytes memory takerAssetData = order.takerAssetData;
bytes memory makerFeeAssetData = order.makerFeeAssetData;
bytes memory takerFeeAssetData = order.takerFeeAssetData;
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_ORDER_SCHEMA_HASH,
// uint256(order.makerAddress),
// uint256(order.takerAddress),
// uint256(order.feeRecipientAddress),
// uint256(order.senderAddress),
// order.makerAssetAmount,
// order.takerAssetAmount,
// order.makerFee,
// order.takerFee,
// order.expirationTimeSeconds,
// order.salt,
// keccak256(order.makerAssetData),
// keccak256(order.takerAssetData),
// keccak256(order.makerFeeAssetData),
// keccak256(order.takerFeeAssetData)
// ));
assembly {
// Assert order offset (this is an internal error that should never be triggered)
if lt(order, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(order, 32)
let pos2 := add(order, 320)
let pos3 := add(order, 352)
let pos4 := add(order, 384)
let pos5 := add(order, 416)
// Backup
let temp1 := mload(pos1)
let temp2 := mload(pos2)
let temp3 := mload(pos3)
let temp4 := mload(pos4)
let temp5 := mload(pos5)
// Hash in place
mstore(pos1, schemaHash)
mstore(pos2, keccak256(add(makerAssetData, 32), mload(makerAssetData))) // store hash of makerAssetData
mstore(pos3, keccak256(add(takerAssetData, 32), mload(takerAssetData))) // store hash of takerAssetData
mstore(pos4, keccak256(add(makerFeeAssetData, 32), mload(makerFeeAssetData))) // store hash of makerFeeAssetData
mstore(pos5, keccak256(add(takerFeeAssetData, 32), mload(takerFeeAssetData))) // store hash of takerFeeAssetData
result := keccak256(pos1, 480)
// Restore
mstore(pos1, temp1)
mstore(pos2, temp2)
mstore(pos3, temp3)
mstore(pos4, temp4)
mstore(pos5, temp5)
}
return result;
}
}
// File: @0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol
/*
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.9;
contract IERC20Token {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/// @dev send `value` token to `to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return True if transfer was successful
function transfer(address _to, uint256 _value)
external
returns (bool);
/// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return True if transfer was successful
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool);
/// @dev `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address _spender, uint256 _value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address _owner)
external
view
returns (uint256);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender)
external
view
returns (uint256);
}
// File: @0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol
/*
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.9;
contract IEtherToken is
IERC20Token
{
function deposit()
public
payable;
function withdraw(uint256 amount)
public;
}
// File: contracts/external/dydx/lib/Account.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @title Account
* @author dYdX
*
* Library of structs and functions that represent an account
*/
library Account {
// Represents the unique key that specifies an account
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
// File: contracts/external/dydx/lib/Types.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
/**
* @title Types
* @author dYdX
*
* Library for interacting with the basic structs used in Solo
*/
library Types {
// ============ AssetAmount ============
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
// ============ Par (Principal Amount) ============
// Individual principal amount for an account
struct Par {
bool sign; // true if positive
uint128 value;
}
// ============ Wei (Token Amount) ============
// Individual token amount for an account
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
// File: contracts/external/dydx/Getters.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
/**
* @title Getters
* @author dYdX
*
* Public read-only functions that allow transparency into the state of Solo
*/
contract Getters {
using Types for Types.Par;
/**
* Get an account's summary for each market.
*
* @param account The account to query
* @return The following values:
* - The ERC20 token address for each market
* - The account's principal value for each market
* - The account's (supplied or borrowed) number of tokens for each market
*/
function getAccountBalances(
Account.Info memory account
)
public
view
returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
}
// File: contracts/external/dydx/lib/Actions.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
/**
* @title Actions
* @author dYdX
*
* Library that defines and parses valid Actions
*/
library Actions {
// ============ Enums ============
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
// ============ Structs ============
/*
* Arguments that are passed to Solo in an ordered list as part of a single operation.
* Each ActionArgs has an actionType which specifies which action struct that this data will be
* parsed into before being processed.
*/
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
// File: contracts/external/dydx/Operation.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
/**
* @title Operation
* @author dYdX
*
* Primary public function for allowing users and contracts to manage accounts within Solo
*/
contract Operation {
/**
* The main entry-point to Solo that allows users and contracts to manage accounts.
* Take one or more actions on one or more accounts. The msg.sender must be the owner or
* operator of all accounts except for those being liquidated, vaporized, or traded with.
* One call to operate() is considered a singular "operation". Account collateralization is
* ensured only after the completion of the entire operation.
*
* @param accounts A list of all accounts that will be used in this operation. Cannot contain
* duplicates. In each action, the relevant account will be referred-to by its
* index in the list.
* @param actions An ordered list of all actions that will be taken in this operation. The
* actions will be processed in order.
*/
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
)
public;
}
// File: contracts/external/dydx/SoloMargin.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
/**
* @title SoloMargin
* @author dYdX
*
* Main contract that inherits from other contracts
*/
contract SoloMargin is
Getters,
Operation
{ }
// File: contracts/lib/pools/DydxPoolController.sol
/**
* COPYRIGHT ยฉ 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title DydxPoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb)
* @dev This library handles deposits to and withdrawals from dYdX liquidity pools.
*/
library DydxPoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address constant private SOLO_MARGIN_CONTRACT = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
SoloMargin constant private _soloMargin = SoloMargin(SOLO_MARGIN_CONTRACT);
uint256 constant private WETH_MARKET_ID = 0;
address constant private WETH_CONTRACT = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IEtherToken constant private _weth = IEtherToken(WETH_CONTRACT);
/**
* @dev Returns the fund's balance of the specified currency in the dYdX pool.
*/
function getBalance() external view returns (uint256) {
Account.Info memory account = Account.Info(address(this), 0);
(, , Types.Wei[] memory weis) = _soloMargin.getAccountBalances(account);
return weis[WETH_MARKET_ID].sign ? weis[WETH_MARKET_ID].value : 0;
}
/**
* @dev Approves WETH to dYdX without spending gas on every deposit.
* @param amount Amount of the WETH to approve to dYdX.
*/
function approve(uint256 amount) external {
uint256 allowance = _weth.allowance(address(this), SOLO_MARGIN_CONTRACT);
if (allowance == amount) return;
if (amount > 0 && allowance > 0) _weth.approve(SOLO_MARGIN_CONTRACT, 0);
_weth.approve(SOLO_MARGIN_CONTRACT, amount);
}
/**
* @dev Deposits funds to the dYdX pool. Assumes that you have already approved >= the amount of WETH to dYdX.
* @param amount The amount of ETH to be deposited.
*/
function deposit(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_weth.deposit.value(amount)();
Account.Info memory account = Account.Info(address(this), 0);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = account;
Types.AssetAmount memory assetAmount = Types.AssetAmount(true, Types.AssetDenomination.Wei, Types.AssetReference.Delta, amount);
bytes memory emptyData;
Actions.ActionArgs memory action = Actions.ActionArgs(
Actions.ActionType.Deposit,
0,
assetAmount,
WETH_MARKET_ID,
0,
address(this),
0,
emptyData
);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
actions[0] = action;
_soloMargin.operate(accounts, actions);
}
/**
* @dev Withdraws funds from the dYdX pool.
* @param amount The amount of ETH to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
Account.Info memory account = Account.Info(address(this), 0);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = account;
Types.AssetAmount memory assetAmount = Types.AssetAmount(false, Types.AssetDenomination.Wei, Types.AssetReference.Delta, amount);
bytes memory emptyData;
Actions.ActionArgs memory action = Actions.ActionArgs(
Actions.ActionType.Withdraw,
0,
assetAmount,
WETH_MARKET_ID,
0,
address(this),
0,
emptyData
);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
actions[0] = action;
_soloMargin.operate(accounts, actions);
_weth.withdraw(amount); // Convert WETH to ETH
}
/**
* @dev Withdraws all funds from the dYdX pool.
*/
function withdrawAll() external {
Account.Info memory account = Account.Info(address(this), 0);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = account;
Types.AssetAmount memory assetAmount = Types.AssetAmount(true, Types.AssetDenomination.Par, Types.AssetReference.Target, 0);
bytes memory emptyData;
Actions.ActionArgs memory action = Actions.ActionArgs(
Actions.ActionType.Withdraw,
0,
assetAmount,
WETH_MARKET_ID,
0,
address(this),
0,
emptyData
);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
actions[0] = action;
_soloMargin.operate(accounts, actions);
_weth.withdraw(_weth.balanceOf(address(this))); // Convert WETH to ETH
}
}
// File: contracts/external/compound/CEther.sol
/**
* Copyright 2020 Compound Labs, Inc.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
pragma solidity 0.5.17;
/**
* @title Compound's CEther Contract
* @notice CToken which wraps Ether
* @author Compound
*/
interface CEther {
function mint() external payable;
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function balanceOf(address account) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
}
// File: contracts/lib/pools/CompoundPoolController.sol
/**
* COPYRIGHT ยฉ 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title CompoundPoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb)
* @dev This library handles deposits to and withdrawals from Compound liquidity pools.
*/
library CompoundPoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address constant private cETH_CONTACT_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
CEther constant private _cETHContract = CEther(cETH_CONTACT_ADDRESS);
/**
* @dev Returns the fund's balance of the specified currency in the Compound pool.
*/
function getBalance() external returns (uint256) {
return _cETHContract.balanceOfUnderlying(address(this));
}
/**
* @dev Deposits funds to the Compound pool. Assumes that you have already approved >= the amount to Compound.
* @param amount The amount of tokens to be deposited.
*/
function deposit(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_cETHContract.mint.value(amount)();
}
/**
* @dev Withdraws funds from the Compound pool.
* @param amount The amount of tokens to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than to 0.");
uint256 redeemResult = _cETHContract.redeemUnderlying(amount);
require(redeemResult == 0, "Error calling redeemUnderlying on Compound cToken: error code not equal to 0");
}
/**
* @dev Withdraws all funds from the Compound pool.
* @return Boolean indicating success.
*/
function withdrawAll() external returns (bool) {
uint256 balance = _cETHContract.balanceOf(address(this));
if (balance <= 0) return false;
uint256 redeemResult = _cETHContract.redeem(balance);
require(redeemResult == 0, "Error calling redeem on Compound cToken: error code not equal to 0");
return true;
}
}
// File: contracts/external/keeperdao/IKToken.sol
pragma solidity 0.5.17;
interface IKToken {
function underlying() external view returns (address);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function mint(address recipient, uint256 amount) external returns (bool);
function burnFrom(address sender, uint256 amount) external;
function addMinter(address sender) external;
function renounceMinter() external;
}
// File: contracts/external/keeperdao/ILiquidityPool.sol
pragma solidity 0.5.17;
interface ILiquidityPool {
function () external payable;
function kToken(address _token) external view returns (IKToken);
function register(IKToken _kToken) external;
function renounceOperator() external;
function deposit(address _token, uint256 _amount) external payable returns (uint256);
function withdraw(address payable _to, IKToken _kToken, uint256 _kTokenAmount) external;
function borrowableBalance(address _token) external view returns (uint256);
function underlyingBalance(address _token, address _owner) external view returns (uint256);
}
// File: contracts/lib/pools/KeeperDaoPoolController.sol
/**
* COPYRIGHT ยฉ 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title KeeperDaoPoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb)
* @dev This library handles deposits to and withdrawals from KeeperDAO liquidity pools.
*/
library KeeperDaoPoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address payable constant private KEEPERDAO_CONTRACT = 0x35fFd6E268610E764fF6944d07760D0EFe5E40E5;
ILiquidityPool constant private _liquidityPool = ILiquidityPool(KEEPERDAO_CONTRACT);
// KeeperDAO's representation of ETH
address constant private ETHEREUM_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/**
* @dev Returns the fund's balance in the KeeperDAO pool.
*/
function getBalance() external view returns (uint256) {
return _liquidityPool.underlyingBalance(ETHEREUM_ADDRESS, address(this));
}
/**
* @dev Approves kEther to KeeperDAO to burn without spending gas on every deposit.
* @param amount Amount of kEther to approve to KeeperDAO.
*/
function approve(uint256 amount) external {
IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS);
uint256 allowance = kEther.allowance(address(this), KEEPERDAO_CONTRACT);
if (allowance == amount) return;
if (amount > 0 && allowance > 0) kEther.approve(KEEPERDAO_CONTRACT, 0);
kEther.approve(KEEPERDAO_CONTRACT, amount);
}
/**
* @dev Deposits funds to the KeeperDAO pool..
* @param amount The amount of ETH to be deposited.
*/
function deposit(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_liquidityPool.deposit.value(amount)(ETHEREUM_ADDRESS, amount);
}
/**
* @dev Withdraws funds from the KeeperDAO pool.
* @param amount The amount of ETH to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_liquidityPool.withdraw(address(uint160(address(this))),
_liquidityPool.kToken(ETHEREUM_ADDRESS),
calculatekEtherWithdrawAmount(amount));
}
/**
* @dev Withdraws all funds from the KeeperDAO pool.
* @return Boolean indicating success.
*/
function withdrawAll() external returns (bool) {
IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS);
uint256 balance = kEther.balanceOf(address(this));
if (balance <= 0) return false;
_liquidityPool.withdraw(address(uint160(address(this))), kEther, balance);
return true;
}
/**
* @dev Calculates an amount of kEther to withdraw equivalent to amount parameter in ETH.
* @return amount to withdraw in kEther.
*/
function calculatekEtherWithdrawAmount(uint256 amount) internal view returns (uint256) {
IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS);
uint256 totalSupply = kEther.totalSupply();
uint256 borrowableBalance = _liquidityPool.borrowableBalance(ETHEREUM_ADDRESS);
uint256 kEtherAmount = amount.mul(totalSupply).div(borrowableBalance);
if (kEtherAmount.mul(borrowableBalance).div(totalSupply) < amount) kEtherAmount++;
return kEtherAmount;
}
}
// File: contracts/external/aave/LendingPool.sol
/**
* Aave Protocol
* Copyright (C) 2019 Aave
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details
*/
pragma solidity 0.5.17;
/**
* @title LendingPool contract
* @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data
* @author Aave
*/
contract LendingPool {
/**
* @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens)
* is minted.
* @param _reserve the address of the reserve
* @param _amount the amount to be deposited
* @param _referralCode integrators are assigned a referral code and can potentially receive rewards.
*/
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external payable;
}
// File: contracts/external/aave/AToken.sol
/**
* Aave Protocol
* Copyright (C) 2019 Aave
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details
*/
pragma solidity 0.5.17;
/**
* @title Aave ERC20 AToken
* @dev Implementation of the interest bearing token for the DLP protocol.
* @author Aave
*/
contract AToken {
/**
* @dev redeems aToken for the underlying asset
* @param _amount the amount being redeemed
*/
function redeem(uint256 _amount) external;
/**
* @dev calculates the balance of the user, which is the
* principal balance + interest generated by the principal balance + interest generated by the redirected balance
* @param _user the user for which the balance is being calculated
* @return the total balance of the user
*/
function balanceOf(address _user) public view returns (uint256);
}
// File: contracts/lib/pools/AavePoolController.sol
/**
* COPYRIGHT ยฉ 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title AavePoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb)
* @dev This library handles deposits to and withdrawals from Aave liquidity pools.
*/
library AavePoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Aave LendingPool contract address.
*/
address constant private LENDING_POOL_CONTRACT = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
/**
* @dev Aave LendingPool contract object.
*/
LendingPool constant private _lendingPool = LendingPool(LENDING_POOL_CONTRACT);
/**
* @dev Aave LendingPoolCore contract address.
*/
address constant private LENDING_POOL_CORE_CONTRACT = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/**
* @dev AETH contract address.
*/
address constant private AETH_CONTRACT = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
/**
* @dev AETH contract.
*/
AToken constant private aETH = AToken(AETH_CONTRACT);
/**
* @dev Ethereum address abstraction
*/
address constant private ETHEREUM_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/**
* @dev Returns the fund's balance of the specified currency in the Aave pool.
*/
function getBalance() external view returns (uint256) {
return aETH.balanceOf(address(this));
}
/**
* @dev Deposits funds to the Aave pool. Assumes that you have already approved >= the amount to Aave.
* @param amount The amount of tokens to be deposited.
* @param referralCode Referral code.
*/
function deposit(uint256 amount, uint16 referralCode) external {
require(amount > 0, "Amount must be greater than 0.");
_lendingPool.deposit.value(amount)(ETHEREUM_ADDRESS, amount, referralCode);
}
/**
* @dev Withdraws funds from the Aave pool.
* @param amount The amount of tokens to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
aETH.redeem(amount);
}
/**
* @dev Withdraws all funds from the Aave pool.
*/
function withdrawAll() external {
aETH.redeem(uint256(-1));
}
}
// File: contracts/external/alpha/Bank.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
contract Bank is IERC20 {
/// @dev Return the total ETH entitled to the token holders. Be careful of unaccrued interests.
function totalETH() public view returns (uint256);
/// @dev Add more ETH to the bank. Hope to get some good returns.
function deposit() external payable;
/// @dev Withdraw ETH from the bank by burning the share tokens.
function withdraw(uint256 share) external;
}
// File: contracts/lib/pools/AlphaPoolController.sol
/**
* COPYRIGHT ยฉ 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title AlphaPoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @dev This library handles deposits to and withdrawals from Alpha Homora's ibETH pool.
*/
library AlphaPoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Alpha Homora ibETH token contract address.
*/
address constant private IBETH_CONTRACT = 0x67B66C99D3Eb37Fa76Aa3Ed1ff33E8e39F0b9c7A;
/**
* @dev Alpha Homora ibETH token contract object.
*/
Bank constant private _ibEth = Bank(IBETH_CONTRACT);
/**
* @dev Returns the fund's balance of the specified currency in the ibETH pool.
*/
function getBalance() external view returns (uint256) {
return _ibEth.balanceOf(address(this)).mul(_ibEth.totalETH()).div(_ibEth.totalSupply());
}
/**
* @dev Deposits funds to the ibETH pool. Assumes that you have already approved >= the amount to the ibETH token contract.
* @param amount The amount of ETH to be deposited.
*/
function deposit(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_ibEth.deposit.value(amount)();
}
/**
* @dev Withdraws funds from the ibETH pool.
* @param amount The amount of tokens to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
uint256 totalEth = _ibEth.totalETH();
uint256 totalSupply = _ibEth.totalSupply();
uint256 credits = amount.mul(totalSupply).div(totalEth);
if (credits.mul(totalEth).div(totalSupply) < amount) credits++; // Round up if necessary (i.e., if the division above left a remainder)
_ibEth.withdraw(credits);
}
/**
* @dev Withdraws all funds from the ibETH pool.
* @return Boolean indicating success.
*/
function withdrawAll() external returns (bool) {
uint256 balance = _ibEth.balanceOf(address(this));
if (balance <= 0) return false;
_ibEth.withdraw(balance);
return true;
}
}
// File: contracts/external/enzyme/ComptrollerLib.sol
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <council@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.5.17;
/// @title ComptrollerLib Contract
/// @author Enzyme Council <security@enzyme.finance>
/// @notice The core logic library shared by all funds
interface ComptrollerLib {
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return grossShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue(bool _requireFinality)
external
returns (uint256 grossShareValue_, bool isValid_);
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares in the fund for multiple sets of criteria
/// @param _buyers The accounts for which to buy shares
/// @param _investmentAmounts The amounts of the fund's denomination asset
/// with which to buy shares for the corresponding _buyers
/// @param _minSharesQuantities The minimum quantities of shares to buy
/// with the corresponding _investmentAmounts
/// @return sharesReceivedAmounts_ The actual amounts of shares received
/// by the corresponding _buyers
/// @dev Param arrays have indexes corresponding to individual __buyShares() orders.
function buyShares(
address[] calldata _buyers,
uint256[] calldata _investmentAmounts,
uint256[] calldata _minSharesQuantities
) external returns (uint256[] memory sharesReceivedAmounts_);
// REDEEM SHARES
/// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev See __redeemShares() for further detail
function redeemShares()
external
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_);
/// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of
/// the fund's assets, optionally specifying additional assets and assets to skip.
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
function redeemSharesDetailed(
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
)
external
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_);
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() external view returns (address vaultProxy_);
}
// File: contracts/lib/pools/EnzymePoolController.sol
/**
* COPYRIGHT ยฉ 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title EnzymePoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @dev This library handles deposits to and withdrawals from Enzyme's Rari ETH (technically WETH) pool.
*/
library EnzymePoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev The WETH contract address.
*/
address constant private WETH_CONTRACT = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/**
* @dev The WETH contract object.
*/
IEtherToken constant private _weth = IEtherToken(WETH_CONTRACT);
/**
* @dev Alpha Homora ibETH token contract address.
*/
address constant private IBETH_CONTRACT = 0x67B66C99D3Eb37Fa76Aa3Ed1ff33E8e39F0b9c7A;
/**
* @dev Returns the fund's balance of ETH (technically WETH) in the Enzyme pool.
*/
function getBalance(address comptroller) external returns (uint256) {
ComptrollerLib _comptroller = ComptrollerLib(comptroller);
(uint256 price, bool valid) = _comptroller.calcGrossShareValue(true);
require(valid, "Enzyme gross share value not valid.");
return IERC20(_comptroller.getVaultProxy()).balanceOf(address(this)).mul(price).div(1e18);
}
/**
* @dev Approves WETH to the Enzyme pool Comptroller without spending gas on every deposit.
* @param comptroller The Enzyme pool Comptroller contract address.
* @param amount Amount of the WETH to approve to the Enzyme pool Comptroller.
*/
function approve(address comptroller, uint256 amount) external {
uint256 allowance = _weth.allowance(address(this), comptroller);
if (allowance == amount) return;
if (amount > 0 && allowance > 0) _weth.approve(comptroller, 0);
_weth.approve(comptroller, amount);
}
/**
* @dev Deposits funds to the Enzyme pool. Assumes that you have already approved >= the amount to the Enzyme Comptroller contract.
* @param comptroller The Enzyme pool Comptroller contract address.
* @param amount The amount of ETH to be deposited.
*/
function deposit(address comptroller, uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_weth.deposit.value(amount)();
address[] memory buyers = new address[](1);
buyers[0] = address(this);
uint256[] memory amounts = new uint256[](1);
amounts[0] = amount;
uint256[] memory minShares = new uint256[](1);
minShares[0] = 0;
ComptrollerLib(comptroller).buyShares(buyers, amounts, minShares);
}
/**
* @dev Withdraws funds from the Enzyme pool.
* @param comptroller The Enzyme pool Comptroller contract address.
* @param amount The amount of tokens to be withdrawn.
*/
function withdraw(address comptroller, uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
ComptrollerLib _comptroller = ComptrollerLib(comptroller);
(uint256 price, bool valid) = _comptroller.calcGrossShareValue(true);
require(valid, "Enzyme gross share value not valid.");
uint256 shares = amount.mul(1e18).div(price);
if (shares.mul(price).div(1e18) < amount) shares++; // Round up if necessary (i.e., if the division above left a remainder)
address[] memory additionalAssets = new address[](0);
address[] memory assetsToSkip = new address[](0);
_comptroller.redeemSharesDetailed(shares, additionalAssets, assetsToSkip);
_weth.withdraw(_weth.balanceOf(address(this)));
}
/**
* @dev Withdraws all funds from the Enzyme pool.
* @param comptroller The Enzyme pool Comptroller contract address.
*/
function withdrawAll(address comptroller) external {
ComptrollerLib(comptroller).redeemShares();
_weth.withdraw(_weth.balanceOf(address(this)));
}
}
// File: @0x/contracts-utils/contracts/src/LibRichErrors.sol
/*
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.9;
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR =
0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
// File: @0x/contracts-utils/contracts/src/LibSafeMathRichErrors.sol
pragma solidity ^0.5.9;
library LibSafeMathRichErrors {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
// File: @0x/contracts-utils/contracts/src/LibSafeMath.sol
pragma solidity ^0.5.9;
library LibSafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
// File: @0x/contracts-exchange-libs/contracts/src/LibMathRichErrors.sol
pragma solidity ^0.5.9;
library LibMathRichErrors {
// bytes4(keccak256("DivisionByZeroError()"))
bytes internal constant DIVISION_BY_ZERO_ERROR =
hex"a791837c";
// bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
bytes4 internal constant ROUNDING_ERROR_SELECTOR =
0x339f3de2;
// solhint-disable func-name-mixedcase
function DivisionByZeroError()
internal
pure
returns (bytes memory)
{
return DIVISION_BY_ZERO_ERROR;
}
function RoundingError(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ROUNDING_ERROR_SELECTOR,
numerator,
denominator,
target
);
}
}
// File: @0x/contracts-exchange-libs/contracts/src/LibMath.sol
/*
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.9;
library LibMath {
using LibSafeMath for uint256;
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorFloor(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorCeil(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
}
// File: @0x/contracts-exchange-libs/contracts/src/LibFillResults.sol
/*
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.9;
library LibFillResults {
using LibSafeMath for uint256;
struct BatchMatchedFillResults {
FillResults[] left; // Fill results for left orders
FillResults[] right; // Fill results for right orders
uint256 profitInLeftMakerAsset; // Profit taken from left makers
uint256 profitInRightMakerAsset; // Profit taken from right makers
}
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s).
uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract.
}
struct MatchedFillResults {
FillResults left; // Amounts filled and fees paid of left order.
FillResults right; // Amounts filled and fees paid of right order.
uint256 profitInLeftMakerAsset; // Profit taken from the left maker
uint256 profitInRightMakerAsset; // Profit taken from the right maker
}
/// @dev Calculates amounts filled and fees paid by maker and taker.
/// @param order to be filled.
/// @param takerAssetFilledAmount Amount of takerAsset that will be filled.
/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.
/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue
/// to be pure rather than view.
/// @return fillResults Amounts filled and fees paid by maker and taker.
function calculateFillResults(
LibOrder.Order memory order,
uint256 takerAssetFilledAmount,
uint256 protocolFeeMultiplier,
uint256 gasPrice
)
internal
pure
returns (FillResults memory fillResults)
{
// Compute proportional transfer amounts
fillResults.takerAssetFilledAmount = takerAssetFilledAmount;
fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerAssetAmount
);
fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerFee
);
fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.takerFee
);
// Compute the protocol fee that should be paid for a single fill.
fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier);
return fillResults;
}
/// @dev Calculates fill amounts for the matched orders.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the leftOrder order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftOrderTakerAssetFilledAmount Amount of left order already filled.
/// @param rightOrderTakerAssetFilledAmount Amount of right order already filled.
/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.
/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue
/// to be pure rather than view.
/// @param shouldMaximallyFillOrders A value that indicates whether or not this calculation should use
/// the maximal fill order matching strategy.
/// @param matchedFillResults Amounts to fill and fees to pay by maker and taker of matched orders.
function calculateMatchedFillResults(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftOrderTakerAssetFilledAmount,
uint256 rightOrderTakerAssetFilledAmount,
uint256 protocolFeeMultiplier,
uint256 gasPrice,
bool shouldMaximallyFillOrders
)
internal
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Derive maker asset amounts for left & right orders, given store taker assert amounts
uint256 leftTakerAssetAmountRemaining = leftOrder.takerAssetAmount.safeSub(leftOrderTakerAssetFilledAmount);
uint256 leftMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor(
leftOrder.makerAssetAmount,
leftOrder.takerAssetAmount,
leftTakerAssetAmountRemaining
);
uint256 rightTakerAssetAmountRemaining = rightOrder.takerAssetAmount.safeSub(rightOrderTakerAssetFilledAmount);
uint256 rightMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor(
rightOrder.makerAssetAmount,
rightOrder.takerAssetAmount,
rightTakerAssetAmountRemaining
);
// Maximally fill the orders and pay out profits to the matcher in one or both of the maker assets.
if (shouldMaximallyFillOrders) {
matchedFillResults = _calculateMatchedFillResultsWithMaximalFill(
leftOrder,
rightOrder,
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else {
matchedFillResults = _calculateMatchedFillResults(
leftOrder,
rightOrder,
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Compute fees for left order
matchedFillResults.left.makerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.left.makerAssetFilledAmount,
leftOrder.makerAssetAmount,
leftOrder.makerFee
);
matchedFillResults.left.takerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.left.takerAssetFilledAmount,
leftOrder.takerAssetAmount,
leftOrder.takerFee
);
// Compute fees for right order
matchedFillResults.right.makerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.right.makerAssetFilledAmount,
rightOrder.makerAssetAmount,
rightOrder.makerFee
);
matchedFillResults.right.takerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.right.takerAssetFilledAmount,
rightOrder.takerAssetAmount,
rightOrder.takerFee
);
// Compute the protocol fee that should be paid for a single fill. In this
// case this should be made the protocol fee for both the left and right orders.
uint256 protocolFee = gasPrice.safeMul(protocolFeeMultiplier);
matchedFillResults.left.protocolFeePaid = protocolFee;
matchedFillResults.right.protocolFeePaid = protocolFee;
// Return fill results
return matchedFillResults;
}
/// @dev Adds properties of both FillResults instances.
/// @param fillResults1 The first FillResults.
/// @param fillResults2 The second FillResults.
/// @return The sum of both fill results.
function addFillResults(
FillResults memory fillResults1,
FillResults memory fillResults2
)
internal
pure
returns (FillResults memory totalFillResults)
{
totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount);
totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount);
totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid);
totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid);
totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid);
return totalFillResults;
}
/// @dev Calculates part of the matched fill results for a given situation using the fill strategy that only
/// awards profit denominated in the left maker asset.
/// @param leftOrder The left order in the order matching situation.
/// @param rightOrder The right order in the order matching situation.
/// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled.
/// @return MatchFillResults struct that does not include fees paid.
function _calculateMatchedFillResults(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Calculate fill results for maker and taker assets: at least one order will be fully filled.
// The maximum amount the left maker can buy is `leftTakerAssetAmountRemaining`
// The maximum amount the right maker can sell is `rightMakerAssetAmountRemaining`
// We have two distinct cases for calculating the fill results:
// Case 1.
// If the left maker can buy more than the right maker can sell, then only the right order is fully filled.
// If the left maker can buy exactly what the right maker can sell, then both orders are fully filled.
// Case 2.
// If the left maker cannot buy more than the right maker can sell, then only the left order is fully filled.
// Case 3.
// If the left maker can buy exactly as much as the right maker can sell, then both orders are fully filled.
if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) {
// Case 1: Right order is fully filled
matchedFillResults = _calculateCompleteRightFill(
leftOrder,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else if (leftTakerAssetAmountRemaining < rightMakerAssetAmountRemaining) {
// Case 2: Left order is fully filled
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
matchedFillResults.right.makerAssetFilledAmount = leftTakerAssetAmountRemaining;
// Round up to ensure the maker's exchange rate does not exceed the price specified by the order.
// We favor the maker when the exchange rate must be rounded.
matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil(
rightOrder.takerAssetAmount,
rightOrder.makerAssetAmount,
leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount
);
} else {
// leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining
// Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but
// this calculation will be more precise since it does not include rounding.
matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Calculate amount given to taker
matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub(
matchedFillResults.right.takerAssetFilledAmount
);
return matchedFillResults;
}
/// @dev Calculates part of the matched fill results for a given situation using the maximal fill order matching
/// strategy.
/// @param leftOrder The left order in the order matching situation.
/// @param rightOrder The right order in the order matching situation.
/// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled.
/// @return MatchFillResults struct that does not include fees paid.
function _calculateMatchedFillResultsWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// If a maker asset is greater than the opposite taker asset, than there will be a spread denominated in that maker asset.
bool doesLeftMakerAssetProfitExist = leftMakerAssetAmountRemaining > rightTakerAssetAmountRemaining;
bool doesRightMakerAssetProfitExist = rightMakerAssetAmountRemaining > leftTakerAssetAmountRemaining;
// Calculate the maximum fill results for the maker and taker assets. At least one of the orders will be fully filled.
//
// The maximum that the left maker can possibly buy is the amount that the right order can sell.
// The maximum that the right maker can possibly buy is the amount that the left order can sell.
//
// If the left order is fully filled, profit will be paid out in the left maker asset. If the right order is fully filled,
// the profit will be out in the right maker asset.
//
// There are three cases to consider:
// Case 1.
// If the left maker can buy more than the right maker can sell, then only the right order is fully filled.
// Case 2.
// If the right maker can buy more than the left maker can sell, then only the right order is fully filled.
// Case 3.
// If the right maker can sell the max of what the left maker can buy and the left maker can sell the max of
// what the right maker can buy, then both orders are fully filled.
if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) {
// Case 1: Right order is fully filled with the profit paid in the left makerAsset
matchedFillResults = _calculateCompleteRightFill(
leftOrder,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else if (rightTakerAssetAmountRemaining > leftMakerAssetAmountRemaining) {
// Case 2: Left order is fully filled with the profit paid in the right makerAsset.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
// Round down to ensure the right maker's exchange rate does not exceed the price specified by the order.
// We favor the right maker when the exchange rate must be rounded and the profit is being paid in the
// right maker asset.
matchedFillResults.right.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
rightOrder.makerAssetAmount,
rightOrder.takerAssetAmount,
leftMakerAssetAmountRemaining
);
matchedFillResults.right.takerAssetFilledAmount = leftMakerAssetAmountRemaining;
} else {
// Case 3: The right and left orders are fully filled
matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Calculate amount given to taker in the left order's maker asset if the left spread will be part of the profit.
if (doesLeftMakerAssetProfitExist) {
matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub(
matchedFillResults.right.takerAssetFilledAmount
);
}
// Calculate amount given to taker in the right order's maker asset if the right spread will be part of the profit.
if (doesRightMakerAssetProfitExist) {
matchedFillResults.profitInRightMakerAsset = matchedFillResults.right.makerAssetFilledAmount.safeSub(
matchedFillResults.left.takerAssetFilledAmount
);
}
return matchedFillResults;
}
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
/// to the fillResults that are being collected on the order. Both orders will be fully filled in this
/// case.
/// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteFillBoth(
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Calculate the fully filled results for both orders.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
return matchedFillResults;
}
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
/// to the fillResults that are being collected on the order.
/// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts
/// can be derived from this order and the right asset remaining fields.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteRightFill(
LibOrder.Order memory leftOrder,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining;
// Round down to ensure the left maker's exchange rate does not exceed the price specified by the order.
// We favor the left maker when the exchange rate must be rounded and the profit is being paid in the
// left maker asset.
matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
leftOrder.makerAssetAmount,
leftOrder.takerAssetAmount,
rightMakerAssetAmountRemaining
);
return matchedFillResults;
}
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IExchangeCore.sol
/*
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.9;
contract IExchangeCore {
// Fill event is emitted whenever an order is filled.
event Fill(
address indexed makerAddress, // Address that created the order.
address indexed feeRecipientAddress, // Address that received fees.
bytes makerAssetData, // Encoded data specific to makerAsset.
bytes takerAssetData, // Encoded data specific to takerAsset.
bytes makerFeeAssetData, // Encoded data specific to makerFeeAsset.
bytes takerFeeAssetData, // Encoded data specific to takerFeeAsset.
bytes32 indexed orderHash, // EIP712 hash of order (see LibOrder.getTypedDataHash).
address takerAddress, // Address that filled the order.
address senderAddress, // Address that called the Exchange contract (msg.sender).
uint256 makerAssetFilledAmount, // Amount of makerAsset sold by maker and bought by taker.
uint256 takerAssetFilledAmount, // Amount of takerAsset sold by taker and bought by maker.
uint256 makerFeePaid, // Amount of makerFeeAssetData paid to feeRecipient by maker.
uint256 takerFeePaid, // Amount of takerFeeAssetData paid to feeRecipient by taker.
uint256 protocolFeePaid // Amount of eth or weth paid to the staking contract.
);
// Cancel event is emitted whenever an individual order is cancelled.
event Cancel(
address indexed makerAddress, // Address that created the order.
address indexed feeRecipientAddress, // Address that would have recieved fees if order was filled.
bytes makerAssetData, // Encoded data specific to makerAsset.
bytes takerAssetData, // Encoded data specific to takerAsset.
address senderAddress, // Address that called the Exchange contract (msg.sender).
bytes32 indexed orderHash // EIP712 hash of order (see LibOrder.getTypedDataHash).
);
// CancelUpTo event is emitted whenever `cancelOrdersUpTo` is executed succesfully.
event CancelUpTo(
address indexed makerAddress, // Orders cancelled must have been created by this address.
address indexed orderSenderAddress, // Orders cancelled must have a `senderAddress` equal to this address.
uint256 orderEpoch // Orders with specified makerAddress and senderAddress with a salt less than this value are considered cancelled.
);
/// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch
/// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress).
/// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled.
function cancelOrdersUpTo(uint256 targetOrderEpoch)
external
payable;
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev After calling, the order can not be filled anymore.
/// @param order Order struct containing order specifications.
function cancelOrder(LibOrder.Order memory order)
public
payable;
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo);
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IProtocolFees.sol
/*
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.9;
contract IProtocolFees {
// Logs updates to the protocol fee multiplier.
event ProtocolFeeMultiplier(uint256 oldProtocolFeeMultiplier, uint256 updatedProtocolFeeMultiplier);
// Logs updates to the protocolFeeCollector address.
event ProtocolFeeCollectorAddress(address oldProtocolFeeCollector, address updatedProtocolFeeCollector);
/// @dev Allows the owner to update the protocol fee multiplier.
/// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier.
function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier)
external;
/// @dev Allows the owner to update the protocolFeeCollector address.
/// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address.
function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector)
external;
/// @dev Returns the protocolFeeMultiplier
function protocolFeeMultiplier()
external
view
returns (uint256);
/// @dev Returns the protocolFeeCollector address
function protocolFeeCollector()
external
view
returns (address);
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IMatchOrders.sol
/*
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.9;
contract IMatchOrders {
/// @dev Match complementary orders that have a profitable spread.
/// Each order is filled at their respective price point, and
/// the matcher receives a profit denominated in the left maker asset.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults);
/// @dev Match complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrdersWithMaximalFill(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults);
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled by maker and taker of matched orders.
function matchOrdersWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
}
// File: @0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol
/*
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.9;
library LibZeroExTransaction {
using LibZeroExTransaction for ZeroExTransaction;
// Hash for the EIP712 0x transaction schema
// keccak256(abi.encodePacked(
// "ZeroExTransaction(",
// "uint256 salt,",
// "uint256 expirationTimeSeconds,",
// "uint256 gasPrice,",
// "address signerAddress,",
// "bytes data",
// ")"
// ));
bytes32 constant internal _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0xec69816980a3a3ca4554410e60253953e9ff375ba4536a98adfa15cc71541508;
struct ZeroExTransaction {
uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash.
uint256 expirationTimeSeconds; // Timestamp in seconds at which transaction expires.
uint256 gasPrice; // gasPrice that transaction is required to be executed with.
address signerAddress; // Address of transaction signer.
bytes data; // AbiV2 encoded calldata.
}
/// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator.
/// @param transaction 0x transaction structure.
/// @return EIP712 typed data hash of the transaction.
function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 transactionHash)
{
// Hash the transaction with the domain separator of the Exchange contract.
transactionHash = LibEIP712.hashEIP712Message(
eip712ExchangeDomainHash,
transaction.getStructHash()
);
return transactionHash;
}
/// @dev Calculates EIP712 hash of the 0x transaction struct.
/// @param transaction 0x transaction structure.
/// @return EIP712 hash of the transaction struct.
function getStructHash(ZeroExTransaction memory transaction)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH;
bytes memory data = transaction.data;
uint256 salt = transaction.salt;
uint256 expirationTimeSeconds = transaction.expirationTimeSeconds;
uint256 gasPrice = transaction.gasPrice;
address signerAddress = transaction.signerAddress;
// Assembly for more efficiently computing:
// result = keccak256(abi.encodePacked(
// schemaHash,
// salt,
// expirationTimeSeconds,
// gasPrice,
// uint256(signerAddress),
// keccak256(data)
// ));
assembly {
// Compute hash of data
let dataHash := keccak256(add(data, 32), mload(data))
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, schemaHash) // hash of schema
mstore(add(memPtr, 32), salt) // salt
mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds
mstore(add(memPtr, 96), gasPrice) // gasPrice
mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress
mstore(add(memPtr, 160), dataHash) // hash of data
// Compute hash
result := keccak256(memPtr, 192)
}
return result;
}
}
// File: @0x/contracts-exchange/contracts/src/interfaces/ISignatureValidator.sol
/*
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.9;
contract ISignatureValidator {
// Allowed signature types.
enum SignatureType {
Illegal, // 0x00, default value
Invalid, // 0x01
EIP712, // 0x02
EthSign, // 0x03
Wallet, // 0x04
Validator, // 0x05
PreSigned, // 0x06
EIP1271Wallet, // 0x07
NSignatureTypes // 0x08, number of signature types. Always leave at end.
}
event SignatureValidatorApproval(
address indexed signerAddress, // Address that approves or disapproves a contract to verify signatures.
address indexed validatorAddress, // Address of signature validator contract.
bool isApproved // Approval or disapproval of validator contract.
);
/// @dev Approves a hash on-chain.
/// After presigning a hash, the preSign signature type will become valid for that hash and signer.
/// @param hash Any 32-byte hash.
function preSign(bytes32 hash)
external
payable;
/// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf.
/// @param validatorAddress Address of Validator contract.
/// @param approval Approval or disapproval of Validator contract.
function setSignatureValidatorApproval(
address validatorAddress,
bool approval
)
external
payable;
/// @dev Verifies that a hash has been signed by the given signer.
/// @param hash Any 32-byte hash.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid `true` if the signature is valid for the given hash and signer.
function isValidHashSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that a signature for an order is valid.
/// @param order The order.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid true if the signature is valid for the given order and signer.
function isValidOrderSignature(
LibOrder.Order memory order,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that a signature for a transaction is valid.
/// @param transaction The transaction.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid true if the signature is valid for the given transaction and signer.
function isValidTransactionSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that an order, with provided order hash, has been signed
/// by the given signer.
/// @param order The order.
/// @param orderHash The hash of the order.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given order and signer.
function _isValidOrderWithHashSignature(
LibOrder.Order memory order,
bytes32 orderHash,
bytes memory signature
)
internal
view
returns (bool isValid);
/// @dev Verifies that a transaction, with provided order hash, has been signed
/// by the given signer.
/// @param transaction The transaction.
/// @param transactionHash The hash of the transaction.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given transaction and signer.
function _isValidTransactionWithHashSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes32 transactionHash,
bytes memory signature
)
internal
view
returns (bool isValid);
}
// File: @0x/contracts-exchange/contracts/src/interfaces/ITransactions.sol
/*
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.9;
contract ITransactions {
// TransactionExecution event is emitted when a ZeroExTransaction is executed.
event TransactionExecution(bytes32 indexed transactionHash);
/// @dev Executes an Exchange method call in the context of signer.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param signature Proof that transaction has been signed by signer.
/// @return ABI encoded return data of the underlying Exchange function call.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
payable
returns (bytes memory);
/// @dev Executes a batch of Exchange method calls in the context of signer(s).
/// @param transactions Array of 0x transactions containing salt, signerAddress, and data.
/// @param signatures Array of proofs that transactions have been signed by signer(s).
/// @return Array containing ABI encoded return data for each of the underlying Exchange function calls.
function batchExecuteTransactions(
LibZeroExTransaction.ZeroExTransaction[] memory transactions,
bytes[] memory signatures
)
public
payable
returns (bytes[] memory);
/// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`).
/// If calling a fill function, this address will represent the taker.
/// If calling a cancel function, this address will represent the maker.
/// @return Signer of 0x transaction if entry point is `executeTransaction`.
/// `msg.sender` if entry point is any other function.
function _getCurrentContextAddress()
internal
view
returns (address);
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IAssetProxyDispatcher.sol
/*
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.9;
contract IAssetProxyDispatcher {
// Logs registration of new asset proxy
event AssetProxyRegistered(
bytes4 id, // Id of new registered AssetProxy.
address assetProxy // Address of new registered AssetProxy.
);
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external;
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address);
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IWrapperFunctions.sol
/*
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.9;
contract IWrapperFunctions {
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of fillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrKillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrKillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Minimum amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Minimum amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of cancelOrder.
/// @param orders Array of order specifications.
function batchCancelOrders(LibOrder.Order[] memory orders)
public
payable;
}
// File: @0x/contracts-exchange/contracts/src/interfaces/ITransferSimulator.sol
/*
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.9;
contract ITransferSimulator {
/// @dev This function may be used to simulate any amount of transfers
/// As they would occur through the Exchange contract. Note that this function
/// will always revert, even if all transfers are successful. However, it may
/// be used with eth_call or with a try/catch pattern in order to simulate
/// the results of the transfers.
/// @param assetData Array of asset details, each encoded per the AssetProxy contract specification.
/// @param fromAddresses Array containing the `from` addresses that correspond with each transfer.
/// @param toAddresses Array containing the `to` addresses that correspond with each transfer.
/// @param amounts Array containing the amounts that correspond to each transfer.
/// @return This function does not return a value. However, it will always revert with
/// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful.
function simulateDispatchTransferFromCalls(
bytes[] memory assetData,
address[] memory fromAddresses,
address[] memory toAddresses,
uint256[] memory amounts
)
public;
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IExchange.sol
/*
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.9;
// solhint-disable no-empty-blocks
contract IExchange is
IProtocolFees,
IExchangeCore,
IMatchOrders,
ISignatureValidator,
ITransactions,
IAssetProxyDispatcher,
ITransferSimulator,
IWrapperFunctions
{}
// File: contracts/lib/exchanges/ZeroExExchangeController.sol
/**
* COPYRIGHT ยฉ 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title ZeroExExchangeController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @dev This library handles exchanges via 0x.
*/
library ZeroExExchangeController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address constant private EXCHANGE_CONTRACT = 0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef;
IExchange constant private _exchange = IExchange(EXCHANGE_CONTRACT);
address constant private ERC20_PROXY_CONTRACT = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
/**
* @dev Gets allowance of the specified token to 0x.
* @param erc20Contract The ERC20 contract address of the token.
*/
function allowance(address erc20Contract) internal view returns (uint256) {
return IERC20(erc20Contract).allowance(address(this), ERC20_PROXY_CONTRACT);
}
/**
* @dev Approves tokens to 0x without spending gas on every deposit.
* @param erc20Contract The ERC20 contract address of the token.
* @param amount Amount of the specified token to approve to dYdX.
* @return Boolean indicating success.
*/
function approve(address erc20Contract, uint256 amount) internal returns (bool) {
IERC20 token = IERC20(erc20Contract);
uint256 _allowance = token.allowance(address(this), ERC20_PROXY_CONTRACT);
if (_allowance == amount) return true;
if (amount > 0 && _allowance > 0) token.safeApprove(ERC20_PROXY_CONTRACT, 0);
token.safeApprove(ERC20_PROXY_CONTRACT, amount);
return true;
}
/**
* @dev Market sells to 0x exchange orders up to a certain amount of input.
* @param orders The limit orders to be filled in ascending order of price.
* @param signatures The signatures for the orders.
* @param takerAssetFillAmount The amount of the taker asset to sell (excluding taker fees).
* @param protocolFee The protocol fee in ETH to pay to 0x.
* @return Array containing the taker asset filled amount (sold) and maker asset filled amount (bought).
*/
function marketSellOrdersFillOrKill(LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 takerAssetFillAmount, uint256 protocolFee) internal returns (uint256[2] memory) {
require(orders.length > 0, "At least one order and matching signature is required.");
require(orders.length == signatures.length, "Mismatch between number of orders and signatures.");
require(takerAssetFillAmount > 0, "Taker asset fill amount must be greater than 0.");
LibFillResults.FillResults memory fillResults = _exchange.marketSellOrdersFillOrKill.value(protocolFee)(orders, takerAssetFillAmount, signatures);
return [fillResults.takerAssetFilledAmount, fillResults.makerAssetFilledAmount];
}
/**
* @dev Market buys from 0x exchange orders up to a certain amount of output.
* @param orders The limit orders to be filled in ascending order of price.
* @param signatures The signatures for the orders.
* @param makerAssetFillAmount The amount of the maker asset to buy.
* @param protocolFee The protocol fee in ETH to pay to 0x.
* @return Array containing the taker asset filled amount (sold) and maker asset filled amount (bought).
*/
function marketBuyOrdersFillOrKill(LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 makerAssetFillAmount, uint256 protocolFee) internal returns (uint256[2] memory) {
require(orders.length > 0, "At least one order and matching signature is required.");
require(orders.length == signatures.length, "Mismatch between number of orders and signatures.");
require(makerAssetFillAmount > 0, "Maker asset fill amount must be greater than 0.");
LibFillResults.FillResults memory fillResults = _exchange.marketBuyOrdersFillOrKill.value(protocolFee)(orders, makerAssetFillAmount, signatures);
return [fillResults.takerAssetFilledAmount, fillResults.makerAssetFilledAmount];
}
}
// File: contracts/RariFundController.sol
/**
* COPYRIGHT ยฉ 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title RariFundController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb)
* @dev This contract handles deposits to and withdrawals from the liquidity pools that power the Rari Ethereum Pool as well as currency exchanges via 0x.
*/
contract RariFundController is Ownable {
using SafeMath for uint256;
using SignedSafeMath for int256;
using SafeERC20 for IERC20;
/**
* @dev Boolean to be checked on `upgradeFundController`.
*/
bool public constant IS_RARI_FUND_CONTROLLER = true;
/**
* @dev Boolean that, if true, disables the primary functionality of this RariFundController.
*/
bool private _fundDisabled;
/**
* @dev Address of the RariFundManager.
*/
address payable private _rariFundManagerContract;
/**
* @dev Address of the rebalancer.
*/
address private _rariFundRebalancerAddress;
/**
* @dev Enum for liqudity pools supported by Rari.
*/
enum LiquidityPool { dYdX, Compound, KeeperDAO, Aave, Alpha, Enzyme }
/**
* @dev Maps arrays of supported pools to currency codes.
*/
uint8[] private _supportedPools;
/**
* @dev COMP token address.
*/
address constant private COMP_TOKEN = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
/**
* @dev ROOK token address.
*/
address constant private ROOK_TOKEN = 0xfA5047c9c78B8877af97BDcb85Db743fD7313d4a;
/**
* @dev WETH token contract.
*/
IEtherToken constant private _weth = IEtherToken(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
/**
* @dev Caches the balances for each pool, with the sum cached at the end
*/
uint256[] private _cachedBalances;
/**
* @dev Constructor that sets supported ERC20 token contract addresses and supported pools for each supported token.
*/
constructor () public {
Ownable.initialize(msg.sender);
// Add supported pools
addPool(0); // dYdX
addPool(1); // Compound
addPool(2); // KeeperDAO
addPool(3); // Aave
addPool(4); // Alpha
addPool(5); // Enzyme
}
/**
* @dev Adds a supported pool for a token.
* @param pool Pool ID to be supported.
*/
function addPool(uint8 pool) internal {
_supportedPools.push(pool);
}
/**
* @dev Payable fallback function called by 0x exchange to refund unspent protocol fee.
*/
function () external payable { }
/**
* @dev Emitted when the RariFundManager of the RariFundController is set.
*/
event FundManagerSet(address newAddress);
/**
* @dev Sets or upgrades the RariFundManager of the RariFundController.
* @param newContract The address of the new RariFundManager contract.
*/
function setFundManager(address payable newContract) external onlyOwner {
_rariFundManagerContract = newContract;
emit FundManagerSet(newContract);
}
/**
* @dev Throws if called by any account other than the RariFundManager.
*/
modifier onlyManager() {
require(_rariFundManagerContract == msg.sender, "Caller is not the fund manager.");
_;
}
/**
* @dev Emitted when the rebalancer of the RariFundController is set.
*/
event FundRebalancerSet(address newAddress);
/**
* @dev Sets or upgrades the rebalancer of the RariFundController.
* @param newAddress The Ethereum address of the new rebalancer server.
*/
function setFundRebalancer(address newAddress) external onlyOwner {
_rariFundRebalancerAddress = newAddress;
emit FundRebalancerSet(newAddress);
}
/**
* @dev Throws if called by any account other than the rebalancer.
*/
modifier onlyRebalancer() {
require(_rariFundRebalancerAddress == msg.sender, "Caller is not the rebalancer.");
_;
}
/**
* @dev Emitted when the primary functionality of this RariFundController contract has been disabled.
*/
event FundDisabled();
/**
* @dev Emitted when the primary functionality of this RariFundController contract has been enabled.
*/
event FundEnabled();
/**
* @dev Disables primary functionality of this RariFundController so contract(s) can be upgraded.
*/
function disableFund() external onlyOwner {
require(!_fundDisabled, "Fund already disabled.");
_fundDisabled = true;
emit FundDisabled();
}
/**
* @dev Enables primary functionality of this RariFundController once contract(s) are upgraded.
*/
function enableFund() external onlyOwner {
require(_fundDisabled, "Fund already enabled.");
_fundDisabled = false;
emit FundEnabled();
}
/**
* @dev Throws if fund is disabled.
*/
modifier fundEnabled() {
require(!_fundDisabled, "This fund controller contract is disabled. This may be due to an upgrade.");
_;
}
/**
* @dev Sets or upgrades RariFundController by forwarding immediate balance of ETH from the old to the new.
* @param newContract The address of the new RariFundController contract.
*/
function _upgradeFundController(address payable newContract) public onlyOwner {
// Verify fund is disabled + verify new fund controller contract
require(_fundDisabled, "This fund controller contract must be disabled before it can be upgraded.");
require(RariFundController(newContract).IS_RARI_FUND_CONTROLLER(), "New contract does not have IS_RARI_FUND_CONTROLLER set to true.");
// Transfer all ETH to new fund controller
uint256 balance = address(this).balance;
if (balance > 0) {
(bool success, ) = newContract.call.value(balance)("");
require(success, "Failed to transfer ETH.");
}
}
/**
* @dev Sets or upgrades RariFundController by withdrawing all ETH from all pools and forwarding them from the old to the new.
* @param newContract The address of the new RariFundController contract.
*/
function upgradeFundController(address payable newContract) external onlyOwner {
// Withdraw all from Enzyme first because they output other LP tokens
if (hasETHInPool(5))
_withdrawAllFromPool(5);
// Then withdraw all from all other pools
for (uint256 i = 0; i < _supportedPools.length; i++)
if (hasETHInPool(_supportedPools[i]))
_withdrawAllFromPool(_supportedPools[i]);
// Transfer all ETH to new fund controller
_upgradeFundController(newContract);
}
/**
* @dev Returns the fund controller's balance of the specified currency in the specified pool.
* @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state.
* @param pool The index of the pool.
*/
function _getPoolBalance(uint8 pool) public returns (uint256) {
if (pool == 0) return DydxPoolController.getBalance();
else if (pool == 1) return CompoundPoolController.getBalance();
else if (pool == 2) return KeeperDaoPoolController.getBalance();
else if (pool == 3) return AavePoolController.getBalance();
else if (pool == 4) return AlphaPoolController.getBalance();
else if (pool == 5) return EnzymePoolController.getBalance(_enzymeComptroller);
else revert("Invalid pool index.");
}
/**
* @dev Returns the fund controller's balance of the specified currency in the specified pool.
* @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state.
* @param pool The index of the pool.
*/
function getPoolBalance(uint8 pool) public returns (uint256) {
if (!_poolsWithFunds[pool]) return 0;
return _getPoolBalance(pool);
}
/**
* @notice Returns the fund controller's balance of each pool of the specified currency.
* @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `getPoolBalance`) potentially modifies the state.
* @return An array of pool indexes and an array of corresponding balances.
*/
function getEntireBalance() public returns (uint256) {
uint256 sum = address(this).balance; // start with immediate eth balance
for (uint256 i = 0; i < _supportedPools.length; i++) {
sum = getPoolBalance(_supportedPools[i]).add(sum);
}
return sum;
}
/**
* @dev Approves WETH to pool without spending gas on every deposit.
* @param pool The index of the pool.
* @param amount The amount of WETH to be approved.
*/
function approveWethToPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer {
if (pool == 0) return DydxPoolController.approve(amount);
else if (pool == 5) return EnzymePoolController.approve(_enzymeComptroller, amount);
else revert("Invalid pool index.");
}
/**
* @dev Approves kEther to the specified pool without spending gas on every deposit.
* @param amount The amount of kEther to be approved.
*/
function approvekEtherToKeeperDaoPool(uint256 amount) external fundEnabled onlyRebalancer {
KeeperDaoPoolController.approve(amount);
}
/**
* @dev Mapping of bools indicating the presence of funds to pools.
*/
mapping(uint8 => bool) _poolsWithFunds;
/**
* @dev Return a boolean indicating if the fund controller has funds in `currencyCode` in `pool`.
* @param pool The index of the pool to check.
*/
function hasETHInPool(uint8 pool) public view returns (bool) {
return _poolsWithFunds[pool];
}
/**
* @dev Referral code for Aave deposits.
*/
uint16 _aaveReferralCode;
/**
* @dev Sets the referral code for Aave deposits.
* @param referralCode The referral code.
*/
function setAaveReferralCode(uint16 referralCode) external onlyOwner {
_aaveReferralCode = referralCode;
}
/**
* @dev The Enzyme pool Comptroller contract address.
*/
address _enzymeComptroller;
/**
* @dev Sets the Enzyme pool Comptroller contract address.
* @param comptroller The Enzyme pool Comptroller contract address.
*/
function setEnzymeComptroller(address comptroller) external onlyOwner {
_enzymeComptroller = comptroller;
}
/**
* @dev Enum for pool allocation action types supported by Rari.
*/
enum PoolAllocationAction { Deposit, Withdraw, WithdrawAll }
/**
* @dev Emitted when a deposit or withdrawal is made.
* Note that `amount` is not set for `WithdrawAll` actions.
*/
event PoolAllocation(PoolAllocationAction indexed action, LiquidityPool indexed pool, uint256 amount);
/**
* @dev Deposits funds to the specified pool.
* @param pool The index of the pool.
*/
function depositToPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer {
require(amount > 0, "Amount must be greater than 0.");
if (pool == 0) DydxPoolController.deposit(amount);
else if (pool == 1) CompoundPoolController.deposit(amount);
else if (pool == 2) KeeperDaoPoolController.deposit(amount);
else if (pool == 3) AavePoolController.deposit(amount, _aaveReferralCode);
else if (pool == 4) AlphaPoolController.deposit(amount);
else if (pool == 5) EnzymePoolController.deposit(_enzymeComptroller, amount);
else revert("Invalid pool index.");
_poolsWithFunds[pool] = true;
emit PoolAllocation(PoolAllocationAction.Deposit, LiquidityPool(pool), amount);
}
/**
* @dev Internal function to withdraw funds from the specified pool.
* @param pool The index of the pool.
* @param amount The amount of tokens to be withdrawn.
*/
function _withdrawFromPool(uint8 pool, uint256 amount) internal {
if (pool == 0) DydxPoolController.withdraw(amount);
else if (pool == 1) CompoundPoolController.withdraw(amount);
else if (pool == 2) KeeperDaoPoolController.withdraw(amount);
else if (pool == 3) AavePoolController.withdraw(amount);
else if (pool == 4) AlphaPoolController.withdraw(amount);
else if (pool == 5) EnzymePoolController.withdraw(_enzymeComptroller, amount);
else revert("Invalid pool index.");
emit PoolAllocation(PoolAllocationAction.Withdraw, LiquidityPool(pool), amount);
}
/**
* @dev Withdraws funds from the specified pool.
* @param pool The index of the pool.
* @param amount The amount of tokens to be withdrawn.
*/
function withdrawFromPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer {
require(amount > 0, "Amount must be greater than 0.");
_withdrawFromPool(pool, amount);
_poolsWithFunds[pool] = _getPoolBalance(pool) > 0;
}
/**
* @dev Withdraws funds from the specified pool (caching the `initialBalance` parameter).
* @param pool The index of the pool.
* @param amount The amount of tokens to be withdrawn.
* @param initialBalance The fund's balance of the specified currency in the specified pool before the withdrawal.
*/
function withdrawFromPoolKnowingBalance(uint8 pool, uint256 amount, uint256 initialBalance) public fundEnabled onlyManager {
_withdrawFromPool(pool, amount);
if (amount == initialBalance) _poolsWithFunds[pool] = false;
}
/**
* @dev Internal function that withdraws all funds from the specified pool.
* @param pool The index of the pool.
*/
function _withdrawAllFromPool(uint8 pool) internal {
if (pool == 0) DydxPoolController.withdrawAll();
else if (pool == 1) require(CompoundPoolController.withdrawAll(), "No Compound balance to withdraw from.");
else if (pool == 2) require(KeeperDaoPoolController.withdrawAll(), "No KeeperDAO balance to withdraw from.");
else if (pool == 3) AavePoolController.withdrawAll();
else if (pool == 4) require(AlphaPoolController.withdrawAll(), "No Alpha Homora balance to withdraw from.");
else if (pool == 5) EnzymePoolController.withdrawAll(_enzymeComptroller);
else revert("Invalid pool index.");
_poolsWithFunds[pool] = false;
emit PoolAllocation(PoolAllocationAction.WithdrawAll, LiquidityPool(pool), 0);
}
/**
* @dev Withdraws all funds from the specified pool.
* @param pool The index of the pool.
* @return Boolean indicating success.
*/
function withdrawAllFromPool(uint8 pool) external fundEnabled onlyRebalancer {
_withdrawAllFromPool(pool);
}
/**
* @dev Withdraws all funds from the specified pool (without requiring the fund to be enabled).
* @param pool The index of the pool.
* @return Boolean indicating success.
*/
function withdrawAllFromPoolOnUpgrade(uint8 pool) external onlyOwner {
_withdrawAllFromPool(pool);
}
/**
* @dev Withdraws ETH and sends amount to the manager.
* @param amount Amount of ETH to withdraw.
*/
function withdrawToManager(uint256 amount) external onlyManager {
// Input validation
require(amount > 0, "Withdrawal amount must be greater than 0.");
// Check contract balance and withdraw from pools if necessary
uint256 contractBalance = address(this).balance; // get ETH balance
if (contractBalance < amount) {
uint256 poolBalance = getPoolBalance(5);
if (poolBalance > 0) {
uint256 amountLeft = amount.sub(contractBalance);
uint256 poolAmount = amountLeft < poolBalance ? amountLeft : poolBalance;
withdrawFromPoolKnowingBalance(5, poolAmount, poolBalance);
contractBalance = address(this).balance;
}
}
for (uint256 i = 0; i < _supportedPools.length; i++) {
if (contractBalance >= amount) break;
uint8 pool = _supportedPools[i];
if (pool == 5) continue;
uint256 poolBalance = getPoolBalance(pool);
if (poolBalance <= 0) continue;
uint256 amountLeft = amount.sub(contractBalance);
uint256 poolAmount = amountLeft < poolBalance ? amountLeft : poolBalance;
withdrawFromPoolKnowingBalance(pool, poolAmount, poolBalance);
contractBalance = contractBalance.add(poolAmount);
}
require(address(this).balance >= amount, "Too little ETH to transfer.");
(bool success, ) = _rariFundManagerContract.call.value(amount)("");
require(success, "Failed to transfer ETH to RariFundManager.");
}
/**
* @dev Emitted when COMP is exchanged to ETH via 0x.
*/
event CurrencyTrade(address inputErc20Contract, uint256 inputAmount, uint256 outputAmount);
/**
* @dev Approves tokens (COMP or ROOK) to 0x without spending gas on every deposit.
* @param erc20Contract The ERC20 contract address of the token to be approved (must be COMP or ROOK).
* @param amount The amount of tokens to be approved.
*/
function approveTo0x(address erc20Contract, uint256 amount) external fundEnabled onlyRebalancer {
require(erc20Contract == COMP_TOKEN || erc20Contract == ROOK_TOKEN, "Supplied token address is not COMP or ROOK.");
ZeroExExchangeController.approve(erc20Contract, amount);
}
/**
* @dev Market sell (COMP or ROOK) to 0x exchange orders (reverting if `takerAssetFillAmount` is not filled).
* We should be able to make this function external and use calldata for all parameters, but Solidity does not support calldata structs (https://github.com/ethereum/solidity/issues/5479).
* @param inputErc20Contract The input ERC20 token contract address (must be COMP or ROOK).
* @param orders The limit orders to be filled in ascending order of price.
* @param signatures The signatures for the orders.
* @param takerAssetFillAmount The amount of the taker asset to sell (excluding taker fees).
*/
function marketSell0xOrdersFillOrKill(address inputErc20Contract, LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 takerAssetFillAmount) public payable fundEnabled onlyRebalancer {
// Exchange COMP/ROOK to ETH
uint256 ethBalanceBefore = address(this).balance;
uint256[2] memory filledAmounts = ZeroExExchangeController.marketSellOrdersFillOrKill(orders, signatures, takerAssetFillAmount, msg.value);
uint256 ethBalanceAfter = address(this).balance;
emit CurrencyTrade(inputErc20Contract, filledAmounts[0], filledAmounts[1]);
// Unwrap outputted WETH
uint256 wethBalance = _weth.balanceOf(address(this));
require(wethBalance > 0, "No WETH outputted.");
_weth.withdraw(wethBalance);
// Refund unspent ETH protocol fee
uint256 refund = ethBalanceAfter.sub(ethBalanceBefore.sub(msg.value));
if (refund > 0) {
(bool success, ) = msg.sender.call.value(refund)("");
require(success, "Failed to refund unspent ETH protocol fee.");
}
}
/**
* Unwraps all WETH currently owned by the fund controller.
*/
function unwrapAllWeth() external fundEnabled onlyRebalancer {
uint256 wethBalance = _weth.balanceOf(address(this));
require(wethBalance > 0, "No WETH to withdraw.");
_weth.withdraw(wethBalance);
}
/**
* @notice Returns the fund controller's contract ETH balance and balance of each pool (checking `_poolsWithFunds` first to save gas).
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getPoolBalance`) potentially modifies the state.
* @return The fund controller ETH contract balance, an array of pool indexes, and an array of corresponding balances for each pool.
*/
function getRawFundBalances() external returns (uint256, uint8[] memory, uint256[] memory) {
uint8[] memory pools = new uint8[](_supportedPools.length);
uint256[] memory poolBalances = new uint256[](_supportedPools.length);
for (uint256 i = 0; i < _supportedPools.length; i++) {
pools[i] = _supportedPools[i];
poolBalances[i] = getPoolBalance(_supportedPools[i]);
}
return (address(this).balance, pools, poolBalances);
}
}
|
Withdraws funds from the Compound pool. amount The amount of tokens to be withdrawn./
|
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than to 0.");
uint256 redeemResult = _cETHContract.redeemUnderlying(amount);
require(redeemResult == 0, "Error calling redeemUnderlying on Compound cToken: error code not equal to 0");
}
| 12,084,339
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
// Creator: Chiru Labs
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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);
}
/**
* @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;
}
// 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);
}
// 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);
}
// 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);
}
// 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);
}
}
}
}
// 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;
}
}
// 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);
}
}
// 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;
}
}
/**
* @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 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*
* Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply
*/
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 internal currentIndex;
// 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) internal _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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721A: balance query for the zero address"
);
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
unchecked {
for (uint256 curr = tokenId; curr >= 0; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721A: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
override
{
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_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 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 tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
require(quantity != 0, "ERC721A: quantity must be greater than 0");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
require(
_checkOnERC721Received(
address(0),
to,
updatedIndex,
_data
),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
updatedIndex++;
}
currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership
.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721A: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// 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);
}
}
// 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;
}
}
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
/**
* @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.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
*/
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 Merkle 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)
}
}
}
/// @title Hot Dougs
contract HotDougs is Ownable, ReentrancyGuard, ERC721A("Hot Dougs", "DOUGS") {
using Strings for uint256;
using MerkleProof for bytes32[];
/// @notice Max total supply.
uint256 public dougsMax = 6969;
/// @notice Max transaction amount.
uint256 public constant dougsPerTx = 10;
/// @notice Max Dougs per wallet in pre-sale
uint256 public constant dougsMintPerWalletPresale = 3;
/// @notice Total Dougs available in pre-sale
uint256 public constant maxPreSaleDougs = 3000;
/// @notice Dougs price.
uint256 public constant dougsPrice = 0.05 ether;
/// @notice 0 = closed, 1 = pre-sale, 2 = public
uint256 public saleState;
/// @notice Metadata baseURI.
string public baseURI;
/// @notice Metadata unrevealed uri.
string public unrevealedURI;
/// @notice Metadata baseURI extension.
string public baseExtension;
/// @notice OpenSea proxy registry.
address public opensea = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
/// @notice LooksRare marketplace transfer manager.
address public looksrare = 0xf42aa99F011A1fA7CDA90E5E98b277E306BcA83e;
/// @notice Check if marketplaces pre-approve is enabled.
bool public marketplacesApproved = true;
/// @notice Free mint merkle root.
bytes32 public freeMintRoot;
/// @notice Pre-sale merkle root.
bytes32 public preMintRoot;
/// @notice Amount minted by address on free mint.
mapping(address => uint256) public freeMintCount;
/// @notice Amount minted by address on pre access.
mapping(address => uint256) public preMintCount;
/// @notice Authorized callers mapping.
mapping(address => bool) public auth;
modifier canMintDougs(uint256 numberOfTokens) {
require(
totalSupply() + numberOfTokens <= dougsMax,
"Not enough Dougs remaining to mint"
);
_;
}
modifier preSaleActive() {
require(saleState == 1, "Pre sale is not open");
_;
}
modifier publicSaleActive() {
require(saleState == 2, "Public sale is not open");
_;
}
modifier isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root) {
require(
MerkleProof.verify(
merkleProof,
root,
keccak256(abi.encodePacked(msg.sender))
),
"Address does not exist in list"
);
_;
}
modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) {
require(
price * numberOfTokens == msg.value,
"Incorrect ETH value sent"
);
_;
}
modifier maxDougsPerTransaction(uint256 numberOfTokens) {
require(
numberOfTokens <= dougsPerTx,
"Max Dougs to mint per transaction is 10"
);
_;
}
constructor(string memory newUnrevealedURI) {
unrevealedURI = newUnrevealedURI;
}
/// @notice Mint one free token and up to 3 pre-sale tokens.
function mintFree(uint256 numberOfTokens, bytes32[] calldata merkleProof)
external
payable
nonReentrant
preSaleActive
isCorrectPayment(dougsPrice, numberOfTokens - 1)
isValidMerkleProof(merkleProof, freeMintRoot)
{
if (msg.sender != owner()) {
require(
freeMintCount[msg.sender] == 0,
"User already minted a free token"
);
uint256 numAlreadyMinted = preMintCount[msg.sender];
require(
numAlreadyMinted + numberOfTokens - 1 <=
dougsMintPerWalletPresale,
"Max Dougs to mint in pre-sale is three"
);
require(
totalSupply() + numberOfTokens <= maxPreSaleDougs,
"Not enough Dougs remaining in pre-sale"
);
preMintCount[msg.sender] = numAlreadyMinted + numberOfTokens;
freeMintCount[msg.sender]++;
}
_safeMint(msg.sender, numberOfTokens);
}
/// @notice Mint one or more tokens for address on pre-sale list.
function mintPreDoug(uint256 numberOfTokens, bytes32[] calldata merkleProof)
external
payable
nonReentrant
preSaleActive
isCorrectPayment(dougsPrice, numberOfTokens)
isValidMerkleProof(merkleProof, preMintRoot)
{
uint256 numAlreadyMinted = preMintCount[msg.sender];
require(
numAlreadyMinted + numberOfTokens <= dougsMintPerWalletPresale,
"Max Dougs to mint in pre-sale is three"
);
require(
totalSupply() + numberOfTokens <= maxPreSaleDougs,
"Not enough Dougs remaining in pre-sale"
);
preMintCount[msg.sender] += numberOfTokens;
_safeMint(msg.sender, numberOfTokens);
}
/// @notice Mint one or more tokens.
function mintDoug(uint256 numberOfTokens)
external
payable
nonReentrant
publicSaleActive
isCorrectPayment(dougsPrice, numberOfTokens)
canMintDougs(numberOfTokens)
maxDougsPerTransaction(numberOfTokens)
{
_safeMint(msg.sender, numberOfTokens);
}
/// @notice Allow contract owner to mint tokens.
function ownerMint(uint256 numberOfTokens)
external
onlyOwner
canMintDougs(numberOfTokens)
{
_safeMint(msg.sender, numberOfTokens);
}
/// @notice See {IERC721-tokenURI}.
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (bytes(unrevealedURI).length > 0) return unrevealedURI;
return
string(
abi.encodePacked(baseURI, tokenId.toString(), baseExtension)
);
}
/// @notice Set baseURI to `newBaseURI`, baseExtension to `newBaseExtension` and deletes unrevealedURI, triggering a reveal.
function setBaseURI(
string memory newBaseURI,
string memory newBaseExtension
) external onlyOwner {
baseURI = newBaseURI;
baseExtension = newBaseExtension;
delete unrevealedURI;
}
/// @notice Set unrevealedURI to `newUnrevealedURI`.
function setUnrevealedURI(string memory newUnrevealedURI)
external
onlyOwner
{
unrevealedURI = newUnrevealedURI;
}
/// @notice Set sale state. 0 = closed 1 = pre-sale 2 = public.
function setSaleState(uint256 newSaleState) external onlyOwner {
saleState = newSaleState;
}
/// @notice Set freeMintRoot to `newMerkleRoot`.
function setFreeMintRoot(bytes32 newMerkleRoot) external onlyOwner {
freeMintRoot = newMerkleRoot;
}
/// @notice Set preMintRoot to `newMerkleRoot`.
function setPreMintRoot(bytes32 newMerkleRoot) external onlyOwner {
preMintRoot = newMerkleRoot;
}
/// @notice Update Total Supply
function setMaxDougs(uint256 _supply) external onlyOwner {
dougsMax = _supply;
}
/// @notice Toggle marketplaces pre-approve feature.
function toggleMarketplacesApproved() external onlyOwner {
marketplacesApproved = !marketplacesApproved;
}
/// @notice Withdraw balance to Owner
function withdrawMoney() external onlyOwner nonReentrant {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed.");
}
/// @notice See {ERC721-isApprovedForAll}.
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
if (!marketplacesApproved)
return auth[operator] || super.isApprovedForAll(owner, operator);
return
auth[operator] ||
operator == address(ProxyRegistry(opensea).proxies(owner)) ||
operator == looksrare ||
super.isApprovedForAll(owner, operator);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @dev ERC-721 interface for accepting safe transfers.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721TokenReceiver {
/**
* @notice The contract address is always the message sender. A wallet/broker/auction application
* MUST implement the wallet interface if it will accept safe transfers.
* @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the
* recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return
* of other than the magic value MUST result in the transaction being reverted.
* Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing.
* @param _operator The address which called `safeTransferFrom` function.
* @param _from The address which previously owned the token.
* @param _tokenId The NFT identifier which is being transferred.
* @param _data Additional data with no specified format.
* @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
) external returns (bytes4);
}
contract HotDougsMinter is Ownable, ReentrancyGuard, ERC721TokenReceiver {
event Received();
// mapping from dougTokenId to claim status. 0 = available, 1 = claimed
mapping(uint256 => uint256) public claimedDougs;
/// @notice Max Dougs per transaction
uint256 public constant paidDougsPerTx = 10;
/// @notice price of Hot Dougs minted through Minter contract
uint256 public hotDougPrice = .025 ether;
/// @notice original HotDougs Contract Address
address public dougContractAddress;
/// @notice 0 = closed, 1 = pre-sale, 2 = public
uint256 public saleState;
/// @notice Update newDougPrice
function setNewDougPrice(uint256 newDougPrice) external onlyOwner {
hotDougPrice = newDougPrice;
}
/// @notice Max total supply.
uint256 public maxHotDougs = 6969;
/// @notice only allow free dougs until a specified tokenId
uint256 public lastFreeHotDougTokenId;
modifier maxDougsPerTransaction(uint256 numberOfTokens) {
require(
numberOfTokens <= paidDougsPerTx,
"Max Dougs per transaction is 10"
);
_;
}
modifier publicSaleActive() {
require(saleState == 2, "Public sale is not open");
_;
}
modifier canMintDougs(uint256 numberOfTokens) {
require(
dougTotalSupply() + numberOfTokens <= maxHotDougs,
"Not enough Dougs left"
);
_;
}
modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) {
require(
price * numberOfTokens == msg.value,
"Incorrect ETH value sent"
);
_;
}
function dougTotalSupply() public view returns (uint256) {
HotDougs _hotDougs = HotDougs(dougContractAddress);
return _hotDougs.totalSupply();
}
function setDougContractAddress(address originalHotDougAddress)
external
onlyOwner
{
dougContractAddress = originalHotDougAddress;
}
/// ----- Mint Doug Utils -----
/// @notice gets TokenIds for Dougs an address owns
function _getTokenIds(address _owner)
internal
view
returns (uint256[] memory)
{
HotDougs _hotDougs = HotDougs(dougContractAddress);
uint256 tokenBalance = _hotDougs.balanceOf(_owner);
require(tokenBalance > 1, "No Tokens! per _getTokenIds");
uint256[] memory _tokensOfOwner = new uint256[](tokenBalance);
for (uint256 i = 0; i < tokenBalance; i++) {
_tokensOfOwner[i] = _hotDougs.tokenOfOwnerByIndex(_owner, i);
}
return (_tokensOfOwner);
}
/// @notice Get the free dougs eligible by an address
function getFreeDougArray(address _address)
external
view
returns (uint256[] memory)
{
uint256[] memory addressTokenIds = _getTokenIds(_address);
uint256 length = addressTokenIds.length;
uint256[] memory claimableDougs = new uint256[](length);
uint256 j = 0;
for (uint256 i = 0; i < length; i++) {
// check if the token is claimable for a free Doug
if (
claimedDougs[addressTokenIds[i]] == 0 &&
addressTokenIds[i] <= lastFreeHotDougTokenId
) {
// if it is claimable add to the claimable array
claimableDougs[j] = addressTokenIds[i];
j++;
} else {
// remove ineligible Dougs from the claimable array
assembly {
mstore(claimableDougs, sub(mload(claimableDougs), 1))
}
}
}
return claimableDougs;
}
/// @notice check if an address has any Dougs that are claim eligible
function checkForFreeDougs(address _address) public view returns (bool) {
HotDougs _hotDougs = HotDougs(dougContractAddress);
uint256 tokenBalance = _hotDougs.balanceOf(_address);
bool claimableDougs;
if (tokenBalance < 1) {
claimableDougs = false;
} else {
uint256[] memory addressTokenIds = _getTokenIds(_address);
uint256 length = addressTokenIds.length;
for (uint256 i = 0; i < length; i++) {
// check if the token is claimable for a free Doug
if (
claimedDougs[addressTokenIds[i]] == 0 &&
addressTokenIds[i] <= lastFreeHotDougTokenId
) {
// if it is claimable return true if not, keep going to see if any are claimable.
claimableDougs = true;
// leave the loop if any tokens are claimable
break;
} else {
claimableDougs = false;
}
}
}
return claimableDougs;
}
function _mintAndTransferDoug(uint256 _numberOfTokens)
internal
canMintDougs(_numberOfTokens)
{
HotDougs _hotDougs = HotDougs(dougContractAddress);
// get the current number of minted Dougs
uint256 currentTotal = _hotDougs.totalSupply();
// mint the token(s) to this contract
_hotDougs.ownerMint(_numberOfTokens);
// transfer the newly minted Dougs to the minter
for (
uint256 i = currentTotal;
i <= _numberOfTokens + currentTotal - 1;
i++
) {
_hotDougs.transferFrom(address(this), tx.origin, i);
}
}
/// @notice only used in case a token gets "stuck" in the minting contract
function manualTransferContractOwnedDoug(address _to, uint256 _tokenId)
external
onlyOwner
{
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.transferFrom(address(this), _to, _tokenId);
}
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
) external override returns (bytes4) {
_operator;
_from;
_tokenId;
_data;
emit Received();
return 0x150b7a02;
}
/// @notice Set original Hot Doug contract sale state
function setHotDougSaleState(uint256 newSaleState) external onlyOwner {
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.setSaleState(newSaleState);
}
/// @notice Set original Hot Doug BaseURI
function setHotDougBaseURI(
string memory newBaseURI,
string memory newBaseExtension
) external onlyOwner {
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.setBaseURI(newBaseURI, newBaseExtension);
}
/// @notice Set max Dougs on original Hot Dougs contract
function setHotDougMaxDougs(uint256 newMaxDougs) external onlyOwner {
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.setMaxDougs(newMaxDougs);
}
/// @notice Set max Dougs on Hot Dougs Minter contract
function setHotDougMinterMaxDougs(uint256 newMaxDougs) external onlyOwner {
maxHotDougs = newMaxDougs;
}
/// @notice Set sale state. 0 = closed 1 = pre-sale 2 = public.
function setSaleState(uint256 newSaleState) external onlyOwner {
saleState = newSaleState;
}
/// @notice allow the owner to update the maximum tokenId redeemable for a free Doug
function setLastFreeHotDougTokenId(uint256 _tokenId) external onlyOwner {
lastFreeHotDougTokenId = _tokenId;
}
/// --- Money Moves ---
/// @notice moves money from original Hot Dougs contract to Minter contract
function withdrawToMinterContract() external onlyOwner {
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.withdrawMoney();
}
/// @notice moves money to owner of this contract
function withdrawToOwner() external onlyOwner {
(bool success, ) = payable(owner()).call{value: address(this).balance}(
""
);
require(success, "TRANSFER_FAILED");
}
/// ---- Functions to Mint ----
/// @notice Mint a Doug
function mintDougs(uint256 numberToMint)
external
payable
publicSaleActive
isCorrectPayment(hotDougPrice, numberToMint)
canMintDougs(numberToMint)
maxDougsPerTransaction(numberToMint)
nonReentrant
{
_mintAndTransferDoug(numberToMint);
}
/// @notice send a free doug per tokenId to the transaction originator
function sendFreeDougs(uint256[] memory freeDougArray) external {
HotDougs _hotDougs = HotDougs(dougContractAddress);
require(freeDougArray.length > 0);
uint256[] memory addressTokenIds = freeDougArray;
uint256 length = addressTokenIds.length;
require(
dougTotalSupply() + length <= maxHotDougs,
"Not enough Dougs left"
);
// only allow claiming of up to 10 free Dougs at a time
for (uint256 i = 0; i < length && i < 10; i++) {
if (
claimedDougs[addressTokenIds[i]] == 0 &&
addressTokenIds[i] <= lastFreeHotDougTokenId &&
_hotDougs.ownerOf(addressTokenIds[i]) == tx.origin
) {
// add tokenId to list of claimedDougs
claimedDougs[addressTokenIds[i]] = 1;
// mint Doug and transfer to the tx.origin
_mintAndTransferDoug(1);
}
}
}
/// @notice allow the owner of this contract to mint
function ownerMint(uint256 numberOfTokens)
external
onlyOwner
canMintDougs(numberOfTokens)
{
_mintAndTransferDoug(numberOfTokens);
}
/// @notice Transfer the original Hot Doug contract ownership
function transferHotDougOwnership(address newOwner) external onlyOwner {
HotDougs _hotDougs = HotDougs(dougContractAddress);
_hotDougs.transferOwnership(newOwner);
}
/// ###### USED WITH DEBUGGING #######
function getBalance() public view returns (uint256) {
return address(this).balance;
}
receive() external payable {}
}
|
Mint one or more tokens for address on pre-sale list.
|
function mintPreDoug(uint256 numberOfTokens, bytes32[] calldata merkleProof)
external
payable
nonReentrant
preSaleActive
isCorrectPayment(dougsPrice, numberOfTokens)
isValidMerkleProof(merkleProof, preMintRoot)
{
uint256 numAlreadyMinted = preMintCount[msg.sender];
require(
numAlreadyMinted + numberOfTokens <= dougsMintPerWalletPresale,
"Max Dougs to mint in pre-sale is three"
);
require(
totalSupply() + numberOfTokens <= maxPreSaleDougs,
"Not enough Dougs remaining in pre-sale"
);
preMintCount[msg.sender] += numberOfTokens;
_safeMint(msg.sender, numberOfTokens);
}
| 1,132,763
|
./partial_match/1/0xD3ec656617f61324Bc2a2711DBa591295DD0306d/sources/contracts/ERC721PartnerSeaDrop.sol
|
Update the allowed SeaDrop contracts. Only the owner or administrator can use this function. allowedSeaDrop The allowed SeaDrop addresses./
|
function updateAllowedSeaDrop(address[] calldata allowedSeaDrop)
external
override
onlyOwnerOrAdministrator
{
_updateAllowedSeaDrop(allowedSeaDrop);
}
| 3,927,009
|
./full_match/11155111/0x733dcE043088af19443373c839b3a7efEe344817/sources/contracts/KC721.sol
|
this is the mint function they will be using on our mint page Use below line if no batch buy feature require(msg.value >= ((MINTPRICE + (MINTPRICE/50) + (TWO_DOLLARS_ETH)) amount), "Not enough ETH sent; check price!");remove this if and its contents if they dont want presaleif no delayed reveal get rid of this if else and just have the line thats in the else
|
function batchMint(uint256 amount) public payable {
require((mintLive == true && block.timestamp >= mintStartTime) || (presaleActive == true), "Mint is not Live");
require(amount > 0, "Cant mint 0 tokens king");
require(amount <= maxMintPerBatch, "Exceeds max mint per batch");
require(_tokenIdCounter + amount <= MAXSUPPLY, "Max supply reached");
uint256 discountedPrice = getDiscountedPrice(amount);
require(msg.value >= ((discountedPrice + (discountedPrice / 50) + (TWO_DOLLARS_ETH)) * amount), "Not enough ETH sent; check price!");
pendingBalances[OPA] += (MINTPRICE * amount);
pendingBalances[KPA] += ((MINTPRICE/50) + TWO_DOLLARS_ETH) * amount;
if (presaleActive) {
require(presale[msg.sender] == 1, "Sorry King, doesnt look like your address is in the presale");
}
for (uint256 i = 0; i < amount; i++) {
uint256 tokenId = _tokenIdCounter;
_tokenIdCounter++;
_safeMint(msg.sender, tokenId);
if (delayedReveal) {
_setTokenURI(tokenId, _preRevealURI);
_setTokenURI(tokenId, string(abi.encodePacked(_baseTokenURI, "/", tokenId.toString())));
}
}
}
| 3,807,764
|
./partial_match/3/0x65B29b471f69400244Ffee30914745c88883810d/sources/option.sol
|
Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
|
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer();
rounds[round].balances[sender] = rounds[round].balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
rounds[round].balances[recipient] = rounds[round].balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 5,236,944
|
./full_match/43114/0xDc173BfF1F72a6Ca6beFEf0173297a00049322e1/sources/contracts/avax.sol
|
Unchanged OK, check 2
|
function clearStuckBalance(uint256 amountPercentage) external authorized {
uint256 amountBNB = address(this).balance;
payable(marketingFeeReceiver).transfer(amountBNB * amountPercentage / 100);
}
| 4,544,993
|
// 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/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @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: contracts/Interfaces/TokenVestingInterface.sol
pragma solidity 0.6.12;
abstract contract TokenVestingInterface {
event VestingScheduleCreated(
address indexed vestingLocation,
uint32 cliffDuration,
uint32 duration,
uint32 interval,
bool isRevocable
);
event VestingTokensGranted(
address indexed beneficiary,
uint256 vestingAmount,
uint32 startDay,
address vestingLocation
);
event VestingTokensClaimed(address indexed beneficiary, uint256 amount);
event GrantRevoked(address indexed grantHolder);
struct vestingSchedule {
bool isRevocable; /* true if the vesting option is revocable (a gift), false if irrevocable (purchased) */
uint32 cliffDuration; /* Duration of the cliff, with respect to the grant start day, in days. */
uint32 duration; /* Duration of the vesting schedule, with respect to the grant start day, in days. */
uint32 interval; /* Duration in days of the vesting interval. */
}
struct tokenGrant {
bool isActive; /* true if this vesting entry is active and in-effect entry. */
bool wasRevoked; /* true if this vesting schedule was revoked. */
uint32 startDay; /* Start day of the grant, in days since the UNIX epoch (start of day). */
uint256 amount; /* Total number of tokens that vest. */
address vestingLocation; /* Address of wallet that is holding the vesting schedule. */
uint256 claimedAmount; /* Out of vested amount, the amount that has been already transferred to beneficiary */
}
function token() public view virtual returns (IERC20);
function kill(address payable beneficiary) external virtual;
function withdrawTokens(address beneficiary, uint256 amount) external virtual;
// =========================================================================
// === Methods for claiming tokens.
// =========================================================================
function claimVestingTokens(address beneficiary) external virtual;
function claimVestingTokensForAll() external virtual;
// =========================================================================
// === Methods for administratively creating a vesting schedule for an account.
// =========================================================================
function setVestingSchedule(
address vestingLocation,
uint32 cliffDuration,
uint32 duration,
uint32 interval,
bool isRevocable
) external virtual;
// =========================================================================
// === Token grants (general-purpose)
// === Methods to be used for administratively creating one-off token grants with vesting schedules.
// =========================================================================
function addGrant(
address beneficiary,
uint256 vestingAmount,
uint32 startDay,
uint32 duration,
uint32 cliffDuration,
uint32 interval,
bool isRevocable
) public virtual;
function addGrantWithScheduleAt(
address beneficiary,
uint256 vestingAmount,
uint32 startDay,
address vestingLocation
) external virtual;
function addGrantFromToday(
address beneficiary,
uint256 vestingAmount,
uint32 duration,
uint32 cliffDuration,
uint32 interval,
bool isRevocable
) external virtual;
// =========================================================================
// === Check vesting.
// =========================================================================
function today() public view virtual returns (uint32 dayNumber);
function getGrantInfo(address grantHolder, uint32 onDayOrToday)
external
view
virtual
returns (
uint256 amountVested,
uint256 amountNotVested,
uint256 amountOfGrant,
uint256 amountAvailable,
uint256 amountClaimed,
uint32 vestStartDay,
bool isActive,
bool wasRevoked
);
function getScheduleAtInfo(address vestingLocation)
public
view
virtual
returns (
bool isRevocable,
uint32 vestDuration,
uint32 cliffDuration,
uint32 vestIntervalDays
);
function getScheduleInfo(address grantHolder)
external
view
virtual
returns (
bool isRevocable,
uint32 vestDuration,
uint32 cliffDuration,
uint32 vestIntervalDays
);
// =========================================================================
// === Grant revocation
// =========================================================================
function revokeGrant(address grantHolder) external virtual;
}
// File: contracts/Vesting/TokenVesting.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title Contract for token vesting schedules
*
* @dev Contract which gives the ability to act as a pool of funds for allocating
* tokens to any number of other addresses. Token grants support the ability to vest over time in
* accordance a predefined vesting schedule. A given wallet can receive no more than one token grant.
*/
contract TokenVesting is TokenVestingInterface, Context, Ownable {
using SafeMath for uint256;
// Date-related constants for sanity-checking dates to reject obvious erroneous inputs
// and conversions from seconds to days and years that are more or less leap year-aware.
uint32 private constant _THOUSAND_YEARS_DAYS = 365243; /* See https://www.timeanddate.com/date/durationresult.html?m1=1&d1=1&y1=2000&m2=1&d2=1&y2=3000 */
uint32 private constant _TEN_YEARS_DAYS = _THOUSAND_YEARS_DAYS / 100; /* Includes leap years (though it doesn't really matter) */
uint32 private constant _SECONDS_PER_DAY = 24 * 60 * 60; /* 86400 seconds in a day */
uint32 private constant _JAN_1_2000_SECONDS = 946684800; /* Saturday, January 1, 2000 0:00:00 (GMT) (see https://www.epochconverter.com/) */
uint32 private constant _JAN_1_2000_DAYS =
_JAN_1_2000_SECONDS / _SECONDS_PER_DAY;
uint32 private constant _JAN_1_3000_DAYS =
_JAN_1_2000_DAYS + _THOUSAND_YEARS_DAYS;
modifier onlyOwnerOrSelf(address account) {
require(
_msgSender() == owner() || _msgSender() == account,
"onlyOwnerOrSelf"
);
_;
}
mapping(address => vestingSchedule) private _vestingSchedules;
mapping(address => tokenGrant) private _tokenGrants;
address[] private _allBeneficiaries;
IERC20 private _token;
constructor(IERC20 token_) public {
require(address(token_) != address(0), "token must be non-zero address");
_token = token_;
}
function token() public view override returns (IERC20) {
return _token;
}
function kill(address payable beneficiary) external override onlyOwner {
_withdrawTokens(beneficiary, token().balanceOf(address(this)));
selfdestruct(beneficiary);
}
function withdrawTokens(address beneficiary, uint256 amount)
external
override
onlyOwner
{
_withdrawTokens(beneficiary, amount);
}
function _withdrawTokens(address beneficiary, uint256 amount) internal {
require(amount > 0, "amount must be > 0");
require(
amount <= token().balanceOf(address(this)),
"amount must be <= current balance"
);
require(token().transfer(beneficiary, amount));
}
// =========================================================================
// === Methods for claiming tokens.
// =========================================================================
function claimVestingTokens(address beneficiary)
external
override
onlyOwnerOrSelf(beneficiary)
{
_claimVestingTokens(beneficiary);
}
function claimVestingTokensForAll() external override onlyOwner {
for (uint256 i = 0; i < _allBeneficiaries.length; i++) {
_claimVestingTokens(_allBeneficiaries[i]);
}
}
function _claimVestingTokens(address beneficiary) internal {
uint256 amount = _getAvailableAmount(beneficiary, 0);
if (amount > 0) {
_deliverTokens(beneficiary, amount);
_tokenGrants[beneficiary].claimedAmount = _tokenGrants[beneficiary]
.claimedAmount
.add(amount);
emit VestingTokensClaimed(beneficiary, amount);
}
}
function _deliverTokens(address beneficiary, uint256 amount) internal {
require(amount > 0, "amount must be > 0");
require(
amount <= token().balanceOf(address(this)),
"amount must be <= current balance"
);
require(
_tokenGrants[beneficiary].claimedAmount.add(amount) <=
_tokenGrants[beneficiary].amount,
"new claimed amount must be <= total grant amount"
);
require(token().transfer(beneficiary, amount));
}
// =========================================================================
// === Methods for administratively creating a vesting schedule for an account.
// =========================================================================
/**
* @dev This one-time operation permanently establishes a vesting schedule in the given account.
*
* @param cliffDuration = Duration of the cliff, with respect to the grant start day, in days.
* @param duration = Duration of the vesting schedule, with respect to the grant start day, in days.
* @param interval = Number of days between vesting increases.
* @param isRevocable = True if the grant can be revoked (i.e. was a gift) or false if it cannot
* be revoked (i.e. tokens were purchased).
*/
function setVestingSchedule(
address vestingLocation,
uint32 cliffDuration,
uint32 duration,
uint32 interval,
bool isRevocable
) external override onlyOwner {
_setVestingSchedule(
vestingLocation,
cliffDuration,
duration,
interval,
isRevocable
);
}
function _setVestingSchedule(
address vestingLocation,
uint32 cliffDuration,
uint32 duration,
uint32 interval,
bool isRevocable
) internal {
// Check for a valid vesting schedule given (disallow absurd values to reject likely bad input).
require(
duration > 0 &&
duration <= _TEN_YEARS_DAYS &&
cliffDuration < duration &&
interval >= 1,
"invalid vesting schedule"
);
// Make sure the duration values are in harmony with interval (both should be an exact multiple of interval).
require(
duration % interval == 0 && cliffDuration % interval == 0,
"invalid cliff/duration for interval"
);
// Create and populate a vesting schedule.
_vestingSchedules[vestingLocation] = vestingSchedule(
isRevocable,
cliffDuration,
duration,
interval
);
// Emit the event.
emit VestingScheduleCreated(
vestingLocation,
cliffDuration,
duration,
interval,
isRevocable
);
}
// =========================================================================
// === Token grants (general-purpose)
// === Methods to be used for administratively creating one-off token grants with vesting schedules.
// =========================================================================
/**
* @dev Grants tokens to an account.
*
* @param beneficiary = Address to which tokens will be granted.
* @param vestingAmount = The number of tokens subject to vesting.
* @param startDay = Start day of the grant's vesting schedule, in days since the UNIX epoch
* (start of day). The startDay may be given as a date in the future or in the past, going as far
* back as year 2000.
* @param vestingLocation = Account where the vesting schedule is held (must already exist).
*/
function _addGrant(
address beneficiary,
uint256 vestingAmount,
uint32 startDay,
address vestingLocation
) internal {
// Make sure no prior grant is in effect.
require(!_tokenGrants[beneficiary].isActive, "grant already exists");
// Check for valid vestingAmount
require(
vestingAmount > 0 &&
startDay >= _JAN_1_2000_DAYS &&
startDay < _JAN_1_3000_DAYS,
"invalid vesting params"
);
// Create and populate a token grant, referencing vesting schedule.
_tokenGrants[beneficiary] = tokenGrant(
true, // isActive
false, // wasRevoked
startDay,
vestingAmount,
vestingLocation, // The wallet address where the vesting schedule is kept.
0 // claimedAmount
);
_allBeneficiaries.push(beneficiary);
// Emit the event.
emit VestingTokensGranted(
beneficiary,
vestingAmount,
startDay,
vestingLocation
);
}
/**
* @dev Grants tokens to an address, including a portion that will vest over time
* according to a set vesting schedule. The overall duration and cliff duration of the grant must
* be an even multiple of the vesting interval.
*
* @param beneficiary = Address to which tokens will be granted.
* @param vestingAmount = The number of tokens subject to vesting.
* @param startDay = Start day of the grant's vesting schedule, in days since the UNIX epoch
* (start of day). The startDay may be given as a date in the future or in the past, going as far
* back as year 2000.
* @param duration = Duration of the vesting schedule, with respect to the grant start day, in days.
* @param cliffDuration = Duration of the cliff, with respect to the grant start day, in days.
* @param interval = Number of days between vesting increases.
* @param isRevocable = True if the grant can be revoked (i.e. was a gift) or false if it cannot
* be revoked (i.e. tokens were purchased).
*/
function addGrant(
address beneficiary,
uint256 vestingAmount,
uint32 startDay,
uint32 duration,
uint32 cliffDuration,
uint32 interval,
bool isRevocable
) public override onlyOwner {
// Make sure no prior vesting schedule has been set.
require(!_tokenGrants[beneficiary].isActive, "grant already exists");
// The vesting schedule is unique to this wallet and so will be stored here,
_setVestingSchedule(
beneficiary,
cliffDuration,
duration,
interval,
isRevocable
);
// Issue tokens to the beneficiary, using beneficiary's own vesting schedule.
_addGrant(beneficiary, vestingAmount, startDay, beneficiary);
}
function addGrantWithScheduleAt(
address beneficiary,
uint256 vestingAmount,
uint32 startDay,
address vestingLocation
) external override onlyOwner {
// Issue tokens to the beneficiary, using custom vestingLocation.
_addGrant(beneficiary, vestingAmount, startDay, vestingLocation);
}
function addGrantFromToday(
address beneficiary,
uint256 vestingAmount,
uint32 duration,
uint32 cliffDuration,
uint32 interval,
bool isRevocable
) external override onlyOwner {
addGrant(
beneficiary,
vestingAmount,
today(),
duration,
cliffDuration,
interval,
isRevocable
);
}
// =========================================================================
// === Check vesting.
// =========================================================================
function today() public view virtual override returns (uint32 dayNumber) {
return uint32(block.timestamp / _SECONDS_PER_DAY);
}
function _effectiveDay(uint32 onDayOrToday)
internal
view
returns (uint32 dayNumber)
{
return onDayOrToday == 0 ? today() : onDayOrToday;
}
/**
* @dev Determines the amount of tokens that have not vested in the given account.
*
* The math is: not vested amount = vesting amount * (end date - on date)/(end date - start date)
*
* @param grantHolder = The account to check.
* @param onDayOrToday = The day to check for, in days since the UNIX epoch. Can pass
* the special value 0 to indicate today.
*/
function _getNotVestedAmount(address grantHolder, uint32 onDayOrToday)
internal
view
returns (uint256 amountNotVested)
{
tokenGrant storage grant = _tokenGrants[grantHolder];
vestingSchedule storage vesting = _vestingSchedules[grant.vestingLocation];
uint32 onDay = _effectiveDay(onDayOrToday);
// If there's no schedule, or before the vesting cliff, then the full amount is not vested.
if (!grant.isActive || onDay < grant.startDay + vesting.cliffDuration) {
// None are vested (all are not vested)
return grant.amount;
}
// If after end of vesting, then the not vested amount is zero (all are vested).
else if (onDay >= grant.startDay + vesting.duration) {
// All are vested (none are not vested)
return uint256(0);
}
// Otherwise a fractional amount is vested.
else {
// Compute the exact number of days vested.
uint32 daysVested = onDay - grant.startDay;
// Adjust result rounding down to take into consideration the interval.
uint32 effectiveDaysVested = (daysVested / vesting.interval) *
vesting.interval;
// Compute the fraction vested from schedule using 224.32 fixed point math for date range ratio.
// Note: This is safe in 256-bit math because max value of X billion tokens = X*10^27 wei, and
// typical token amounts can fit into 90 bits. Scaling using a 32 bits value results in only 125
// bits before reducing back to 90 bits by dividing. There is plenty of room left, even for token
// amounts many orders of magnitude greater than mere billions.
uint256 vested = grant.amount.mul(effectiveDaysVested).div(
vesting.duration
);
uint256 result = grant.amount.sub(vested);
require(result <= grant.amount && vested <= grant.amount);
return result;
}
}
/**
* @dev Computes the amount of funds in the given account which are available for use as of
* the given day, i.e. the claimable amount.
*
* The math is: available amount = totalGrantAmount - notVestedAmount - claimedAmount.
*
* @param grantHolder = The account to check.
* @param onDay = The day to check for, in days since the UNIX epoch.
*/
function _getAvailableAmount(address grantHolder, uint32 onDay)
internal
view
returns (uint256 amountAvailable)
{
tokenGrant storage grant = _tokenGrants[grantHolder];
return
_getAvailableAmountImpl(grant, _getNotVestedAmount(grantHolder, onDay));
}
function _getAvailableAmountImpl(
tokenGrant storage grant,
uint256 notVastedOnDay
) internal view returns (uint256 amountAvailable) {
uint256 vested = grant.amount.sub(notVastedOnDay);
if (vested < grant.claimedAmount) {
// .sub below will fail, only possible when grant revoked
require(vested == 0 && grant.wasRevoked);
return 0;
}
uint256 result = vested.sub(grant.claimedAmount);
require(
result <= grant.amount &&
grant.claimedAmount.add(result) <= grant.amount &&
result <= vested &&
vested <= grant.amount
);
return result;
}
/**
* @dev returns all information about the grant's vesting as of the given day
* for the given account. Only callable by the account holder or a contract owner.
*
* @param grantHolder = The address to do this for.
* @param onDayOrToday = The day to check for, in days since the UNIX epoch. Can pass
* the special value 0 to indicate today.
* return = A tuple with the following values:
* amountVested = the amount that is already vested
* amountNotVested = the amount that is not yet vested (equal to vestingAmount - vestedAmount)
* amountOfGrant = the total amount of tokens subject to vesting.
* amountAvailable = the amount of funds in the given account which are available for use as of the given day
* amountClaimed = out of amountVested, the amount that has been already transferred to beneficiary
* vestStartDay = starting day of the grant (in days since the UNIX epoch).
* isActive = true if the vesting schedule is currently active.
* wasRevoked = true if the vesting schedule was revoked.
*/
function getGrantInfo(address grantHolder, uint32 onDayOrToday)
external
view
override
returns (
uint256 amountVested,
uint256 amountNotVested,
uint256 amountOfGrant,
uint256 amountAvailable,
uint256 amountClaimed,
uint32 vestStartDay,
bool isActive,
bool wasRevoked
)
{
tokenGrant storage grant = _tokenGrants[grantHolder];
uint256 notVestedAmount = _getNotVestedAmount(grantHolder, onDayOrToday);
return (
grant.amount.sub(notVestedAmount),
notVestedAmount,
grant.amount,
_getAvailableAmountImpl(grant, notVestedAmount),
grant.claimedAmount,
grant.startDay,
grant.isActive,
grant.wasRevoked
);
}
function getScheduleAtInfo(address vestingLocation)
public
view
override
returns (
bool isRevocable,
uint32 vestDuration,
uint32 cliffDuration,
uint32 vestIntervalDays
)
{
vestingSchedule storage vesting = _vestingSchedules[vestingLocation];
return (
vesting.isRevocable,
vesting.duration,
vesting.cliffDuration,
vesting.interval
);
}
function getScheduleInfo(address grantHolder)
external
view
override
returns (
bool isRevocable,
uint32 vestDuration,
uint32 cliffDuration,
uint32 vestIntervalDays
)
{
tokenGrant storage grant = _tokenGrants[grantHolder];
return getScheduleAtInfo(grant.vestingLocation);
}
// =========================================================================
// === Grant revocation
// =========================================================================
/**
* @dev If the account has a revocable grant, this forces the grant to end immediately.
* After this function is called, getGrantInfo will return incomplete data
* and there will be no possibility to claim non-claimed tokens
*
* @param grantHolder = Address to which tokens will be granted.
*/
function revokeGrant(address grantHolder) external override onlyOwner {
tokenGrant storage grant = _tokenGrants[grantHolder];
vestingSchedule storage vesting = _vestingSchedules[grant.vestingLocation];
// Make sure a vesting schedule has previously been set.
require(grant.isActive, "no active grant");
// Make sure it's revocable.
require(vesting.isRevocable, "irrevocable");
// Kill the grant by updating wasRevoked and isActive.
_tokenGrants[grantHolder].wasRevoked = true;
_tokenGrants[grantHolder].isActive = false;
// Emits the GrantRevoked event.
emit GrantRevoked(grantHolder);
}
}
|
Determines the amount of tokens that have not vested in the given account. The math is: not vested amount = vesting amount (end date - on date)/(end date - start date) grantHolder = The account to check. onDayOrToday = The day to check for, in days since the UNIX epoch. Can pass the special value 0 to indicate today./ If there's no schedule, or before the vesting cliff, then the full amount is not vested. None are vested (all are not vested) If after end of vesting, then the not vested amount is zero (all are vested). All are vested (none are not vested) Otherwise a fractional amount is vested. Compute the exact number of days vested. Adjust result rounding down to take into consideration the interval. Compute the fraction vested from schedule using 224.32 fixed point math for date range ratio. Note: This is safe in 256-bit math because max value of X billion tokens = X10^27 wei, and typical token amounts can fit into 90 bits. Scaling using a 32 bits value results in only 125 bits before reducing back to 90 bits by dividing. There is plenty of room left, even for token amounts many orders of magnitude greater than mere billions.
|
function _getNotVestedAmount(address grantHolder, uint32 onDayOrToday)
internal
view
returns (uint256 amountNotVested)
{
tokenGrant storage grant = _tokenGrants[grantHolder];
vestingSchedule storage vesting = _vestingSchedules[grant.vestingLocation];
uint32 onDay = _effectiveDay(onDayOrToday);
if (!grant.isActive || onDay < grant.startDay + vesting.cliffDuration) {
return grant.amount;
}
else if (onDay >= grant.startDay + vesting.duration) {
return uint256(0);
}
else {
uint32 daysVested = onDay - grant.startDay;
uint32 effectiveDaysVested = (daysVested / vesting.interval) *
vesting.interval;
uint256 vested = grant.amount.mul(effectiveDaysVested).div(
vesting.duration
);
uint256 result = grant.amount.sub(vested);
require(result <= grant.amount && vested <= grant.amount);
return result;
}
}
| 327,725
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
import 'hardhat/console.sol';
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import {EnumerableSet} from '@openzeppelin/contracts/utils/EnumerableSet.sol';
import {ITokenStore, TokenStoreWrapper} from './TokenStoreWrapper.sol';
interface IRewardPool {
function collect() external returns (address, uint256);
}
interface IBoardroomV2 {
/* ================= EVENTS ================= */
event DepositShare(address indexed owner, uint256 amount);
event WithdrawShare(address indexed owner, uint256 amount);
event RewardClaimed(
address indexed owner,
address indexed token,
uint256 amount
);
event RewardCollected(
address indexed operator,
address indexed target,
address indexed token,
uint256 amount
);
event RewardCollectionFailedWithReason(
address indexed operator,
address indexed target,
string reason
);
event RewardCollectionFailedWithData(
address indexed operator,
address indexed target,
bytes data
);
/* ================= CALLS ================= */
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function rewardTokensAt(uint256 index) external view returns (address);
function rewardTokensLength() external view returns (uint256);
function rewardPoolsAt(uint256 index) external view returns (address);
function rewardPoolsLength() external view returns (uint256);
function lastSnapshotIndex(address _token) external view returns (uint256);
function rewardEarned(address _token, address _director)
external
view
returns (uint256);
/* ================= TXNS ================= */
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function claimReward() external;
function exit() external;
function collectReward() external;
}
interface IBoardroomV2Gov {
/* ================= EVENTS ================= */
event RewardTokenAdded(address indexed operator, address token);
event RewardTokenRemoved(address indexed operator, address token);
event RewardPoolAdded(address indexed operator, address pool);
event RewardPoolRemoved(address indexed operator, address pool);
/* ================= TXNS ================= */
function migrate() external;
function addRewardToken(address _token) external;
function removeRewardToken(address _token) external;
function addRewardPool(address _pool) external;
function removeRewardPool(address _pool) external;
}
contract BoardroomV2 is
IBoardroomV2,
IBoardroomV2Gov,
TokenStoreWrapper,
Ownable
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/* ================= DATA STRUCTURES ================= */
struct Boardseat {
uint256 lastSnapshotIndex;
uint256 rewardEarned;
}
struct BoardSnapshot {
uint256 at;
uint256 rewardReceived;
uint256 rewardPerShare;
}
/* ================= STATE VARIABLES ================= */
bool public migrated;
EnumerableSet.AddressSet private rewardTokens;
EnumerableSet.AddressSet private rewardPools;
BoardSnapshot genesis =
BoardSnapshot({at: block.number, rewardReceived: 0, rewardPerShare: 0});
mapping(address => BoardSnapshot[]) public history;
mapping(address => mapping(address => Boardseat)) public seats;
/* ================= CONSTRUCTOR ================= */
constructor(
address _cash,
address _share,
address _store
) {
share = IERC20(_share);
store = ITokenStore(_store);
addRewardToken(_cash);
addRewardToken(_share);
}
/* ================= GOV - OWNER ONLY ================= */
/**
* @dev blocks deposit function
*/
function migrate() external override onlyOwner {
migrated = true;
}
/**
* @param _token reward token address
*/
function addRewardToken(address _token) public override onlyOwner {
rewardTokens.add(_token);
history[_token].push(genesis);
emit RewardTokenAdded(_msgSender(), _token);
}
/**
* @param _token reward token address
*/
function removeRewardToken(address _token) public override onlyOwner {
rewardTokens.remove(_token);
emit RewardTokenRemoved(_msgSender(), _token);
}
/**
* @param _pool reward pool address
*/
function addRewardPool(address _pool) public override onlyOwner {
rewardPools.add(_pool);
emit RewardPoolAdded(_msgSender(), _pool);
}
/**
* @param _pool reward pool address
*/
function removeRewardPool(address _pool) public override onlyOwner {
rewardPools.remove(_pool);
emit RewardPoolRemoved(_msgSender(), _pool);
}
/* ================= MODIFIERS ================= */
modifier checkMigration {
require(!migrated, 'Boardroom: migrated');
_;
}
modifier directorExists {
require(store.balanceOf(_msgSender()) > 0, 'Boardroom: absent');
_;
}
/**
* @param _director staker address
*/
modifier updateReward(address _director) {
collectReward();
for (uint256 i = 0; i < rewardTokens.length(); i++) {
address token = rewardTokens.at(i);
if (_director != address(0x0)) {
Boardseat memory seat = seats[token][_director];
seat.rewardEarned = rewardEarned(token, _director);
seat.lastSnapshotIndex = lastSnapshotIndex(token);
seats[token][_director] = seat;
}
}
_;
}
/* ================= CALLS - ANYONE ================= */
/**
* @return total staked amount
*/
function totalSupply() external view override returns (uint256) {
return store.totalSupply();
}
/**
* @param _owner staker address
* @return staker balance
*/
function balanceOf(address _owner)
external
view
override
returns (uint256)
{
return store.balanceOf(_owner);
}
/**
* @param _index of reward token
* @return reward token address
*/
function rewardTokensAt(uint256 _index)
external
view
override
returns (address)
{
return rewardTokens.at(_index);
}
/**
* @return total count of reward tokens
*/
function rewardTokensLength() external view override returns (uint256) {
return rewardTokens.length();
}
/**
* @param _index of reward pool
* @return reward pool address
*/
function rewardPoolsAt(uint256 _index)
external
view
override
returns (address)
{
return rewardPools.at(_index);
}
/**
* @return total count of reward pools
*/
function rewardPoolsLength() external view override returns (uint256) {
return rewardPools.length();
}
/**
* @param _token reward token address
* @return last snapshot index of token history
*/
function lastSnapshotIndex(address _token)
public
view
override
returns (uint256)
{
return history[_token].length.sub(1);
}
/**
* @param _token reward token address
* @return last snapshot of token history
*/
function getLastSnapshot(address _token)
internal
view
returns (BoardSnapshot memory)
{
return history[_token][lastSnapshotIndex(_token)];
}
/**
* @param _token reward token address
* @param _director staker address
* @return last snapshot of director
*/
function getLastSnapshotOf(address _token, address _director)
internal
view
returns (BoardSnapshot memory)
{
return history[_token][seats[_token][_director].lastSnapshotIndex];
}
/**
* @param _token reward token address
* @param _director staker address
* @return reward earned
*/
function rewardEarned(address _token, address _director)
public
view
override
returns (uint256)
{
uint256 latestRPS = getLastSnapshot(_token).rewardPerShare;
uint256 storedRPS = getLastSnapshotOf(_token, _director).rewardPerShare;
return
store
.balanceOf(_director)
.mul(latestRPS.sub(storedRPS))
.div(1e18)
.add(seats[_token][_director].rewardEarned);
}
/* ================= TXNS ================= */
/**
* @dev deposit tokens to boardroom
* @param _amount deposit amount of tokens
*/
function deposit(uint256 _amount)
public
override(IBoardroomV2, TokenStoreWrapper)
checkMigration
updateReward(_msgSender())
{
super.deposit(_amount);
emit DepositShare(_msgSender(), _amount);
}
/**
* @dev withdraw tokens from boardroom
* @param _amount amount of staked tokens
*/
function withdraw(uint256 _amount)
public
override(IBoardroomV2, TokenStoreWrapper)
directorExists
updateReward(_msgSender())
{
super.withdraw(_amount);
emit WithdrawShare(_msgSender(), _amount);
}
/**
* @dev receive collected rewards
*/
function claimReward() public override updateReward(_msgSender()) {
for (uint256 i = 0; i < rewardTokens.length(); i++) {
address token = rewardTokens.at(i);
uint256 reward = seats[token][_msgSender()].rewardEarned;
if (reward > 0) {
seats[token][_msgSender()].rewardEarned = 0;
IERC20(token).safeTransfer(_msgSender(), reward);
emit RewardClaimed(_msgSender(), token, reward);
}
}
}
/**
* @dev withdraw + claim reward
*/
function exit() external override {
withdraw(store.balanceOf(_msgSender()));
claimReward();
}
/**
* @dev collect rewards from pools
*/
function collectReward() public override {
if (store.totalSupply() > 0) {
for (uint256 i = 0; i < rewardPools.length(); i++) {
try IRewardPool(rewardPools.at(i)).collect() returns (
address token,
uint256 amount
) {
if (amount == 0) {
continue;
}
uint256 prevRPS = getLastSnapshot(token).rewardPerShare;
uint256 nextRPS =
prevRPS.add(amount.mul(1e18).div(store.totalSupply()));
BoardSnapshot memory newSnapshot =
BoardSnapshot({
at: block.number,
rewardReceived: amount,
rewardPerShare: nextRPS
});
history[token].push(newSnapshot);
emit RewardCollected(
_msgSender(),
rewardPools.at(i),
token,
amount
);
} catch Error(string memory reason) {
emit RewardCollectionFailedWithReason(
_msgSender(),
rewardPools.at(i),
reason
);
}
}
}
}
}
|
collect rewards from pools/
|
function collectReward() public override {
if (store.totalSupply() > 0) {
for (uint256 i = 0; i < rewardPools.length(); i++) {
try IRewardPool(rewardPools.at(i)).collect() returns (
address token,
uint256 amount
) {
if (amount == 0) {
continue;
}
uint256 prevRPS = getLastSnapshot(token).rewardPerShare;
uint256 nextRPS =
prevRPS.add(amount.mul(1e18).div(store.totalSupply()));
BoardSnapshot memory newSnapshot =
BoardSnapshot({
at: block.number,
rewardReceived: amount,
rewardPerShare: nextRPS
});
history[token].push(newSnapshot);
emit RewardCollected(
_msgSender(),
rewardPools.at(i),
token,
amount
);
emit RewardCollectionFailedWithReason(
_msgSender(),
rewardPools.at(i),
reason
);
}
}
}
}
| 6,417,698
|
pragma solidity ^0.4.8;
// Utility contract for ownership functionality.
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
/**
* @author Ben Hodgson
*
* Sport Betting Contract
*
*/
contract Betting is owned {
using SafeMath for uint;
bytes32 public test;
bytes32 public verify;
// store the authorized leagues
mapping (bytes32 => uint) public leagueIndex;
League[] public leagues;
// constants that control contract functionality
uint public stakeAmount = 10;
struct League {
address host;
string name;
// store the matches
mapping (bytes32 => uint) matchIndex;
Match[] matches;
// store the authorized arbiters
mapping(address => uint) arbiterIndex;
Arbiter[] arbiters;
}
struct Bet {
bytes32 matchHash;
address owner;
string betOnTeam;
uint amount;
bool withdrawn;
}
struct Team {
string name;
uint score;
}
struct Match {
bytes32 hash;
string homeTeam;
string awayTeam;
string league;
uint startTime;
uint commits;
uint reveals;
bool finalized;
mapping (address => uint) betterIndex;
Bet[] bets;
mapping (address => bytes32) resultHash;
mapping (address => bytes32) revealHash;
mapping (bytes32 => uint) resultCountIndex;
Count[] resultCount;
uint betPool;
}
struct Result {
bytes32 hash;
bytes32 matchHash;
Team homeTeam;
Team awayTeam;
}
struct Count {
uint value;
Result matchResult;
}
struct Arbiter {
address id;
uint commits;
uint reveals;
}
constructor() public {
addLeague(owner, "Genesis");
}
/**
* Add League
*
* Make `makerAddress` a league named `leagueName`
*
* @param makerAddress ethereum address to be added as the league host
* @param leagueName public name for that league
*/
function addLeague(
address makerAddress,
string leagueName
) onlyOwner public {
bytes32 leagueHash = keccak256(abi.encodePacked(leagueName));
// Check existence of league.
uint index = leagueIndex[leagueHash];
if (index == 0) {
// Add league to ID list.
leagueIndex[leagueHash] = leagues.length;
// index gets leagues.length, then leagues.length++
index = leagues.length++;
}
// Create and update storage
League storage m = leagues[index];
m.host = makerAddress;
m.name = leagueName;
}
/**
* Remove a league
*
* @notice Remove match maker designation from `makerAddress` address.
*
* @param leagueName the name of the league to be removed
*/
function removeleague(string leagueName) onlyOwner public {
bytes32 leagueHash = validateLeague(leagueName);
// Rewrite the match maker storage to move the 'gap' to the end.
for (uint i = leagueIndex[leagueHash];
i < leagues.length - 1; i++) {
leagues[i] = leagues[i+1];
leagueIndex[keccak256(abi.encodePacked(leagues[i].name))] = i;
}
// Delete the last match maker
delete leagueIndex[leagueHash];
delete leagues[leagues.length-1];
leagues.length--;
}
/**
* Add an Arbiter to a specified League
*
* Make `arbiterAddress` an arbiter for league `leagueName`
*
* @param arbiterAddress ethereum address to be added as a league arbiter
* @param leagueName public name for that league
*/
function addLeagueArbiter(
address arbiterAddress,
string leagueName
) onlyOwner public {
bytes32 leagueHash = validateLeague(leagueName);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
// Check existence of league arbiter
uint index = thisLeague.arbiterIndex[arbiterAddress];
if (index == 0) {
// Add league arbiter to ID list.
thisLeague.arbiterIndex[arbiterAddress] = thisLeague.arbiters.length;
// index gets length, then length++
index = thisLeague.arbiters.length++;
}
// Create and update storage
Arbiter storage a = thisLeague.arbiters[index];
a.id = arbiterAddress;
a.commits = 0;
a.reveals = 0;
}
/**
* Remove an arbiter from a league
*
* @notice Remove arbiter designation from `arbiterAddress` address.
*
* @param arbiterAddress ethereum address to be removed as league arbiter
* @param leagueName the name of the league
*/
function removeLeagueArbiter(
address arbiterAddress,
string leagueName
) onlyOwner public {
bytes32 leagueHash = validateLeagueArbiter(arbiterAddress, leagueName);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
uint index = thisLeague.arbiterIndex[arbiterAddress];
// Rewrite storage to move the 'gap' to the end.
for (uint i = index;
i < thisLeague.arbiters.length - 1; i++) {
thisLeague.arbiters[i] = thisLeague.arbiters[i+1];
thisLeague.arbiterIndex[thisLeague.arbiters[i].id] = i;
}
// Delete the tail
delete thisLeague.arbiterIndex[arbiterAddress];
delete thisLeague.arbiters[thisLeague.arbiters.length-1];
thisLeague.arbiters.length--;
}
/**
* Allows only match makers to create a match
*
* @param homeTeam the home team competing in the match
* @param awayTeam the away team competing in the match
* @param league the match pertains to
* @param startTime the time the match begins
*/
function createMatch(
string homeTeam,
string awayTeam,
string league,
uint startTime
) public returns (bytes32 matchHash) {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
// require this is the league host
require(thisLeague.host == msg.sender, "Sender is not the league host");
// TODO require match hasn't already started
//require(startTime > now + 1 hours, "Match already started");
matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
uint index = thisLeague.matchIndex[matchHash];
if (index == 0) {
thisLeague.matchIndex[matchHash] = thisLeague.matches.length;
index = thisLeague.matches.length++;
}
// Create and update storage
Match storage newMatch = thisLeague.matches[index];
newMatch.hash = matchHash;
newMatch.homeTeam = homeTeam;
newMatch.awayTeam = awayTeam;
newMatch.league = league;
newMatch.startTime = startTime;
newMatch.finalized = false;
}
/**
* Allows only match makers to remove a match. Refunds all bets placed
* on the match.
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function removeMatch(
string homeTeam,
string awayTeam,
string league,
uint startTime
) public {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
// require this is the league host
require(thisLeague.host == msg.sender, "Sender is not the league host");
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
uint index = thisLeague.matchIndex[matchHash];
require(thisLeague.matches[index].hash == matchHash, "Invalid match");
// require the match hasn't started
require(now < thisLeague.matches[index].startTime, "Match has started");
// refund bets
for (uint b = 0; b < thisLeague.matches[index].bets.length; b++) {
if (!thisLeague.matches[index].bets[b].withdrawn) {
Bet storage thisBet = thisLeague.matches[index].bets[b];
thisBet.withdrawn = true;
thisBet.owner.transfer(thisBet.amount);
}
}
// Rewrite the matches storage to move the 'gap' to the end.
for (uint i = thisLeague.matchIndex[matchHash];
i < thisLeague.matches.length - 1; i++) {
thisLeague.matches[i] = thisLeague.matches[i + 1];
thisLeague.matchIndex[thisLeague.matches[i].hash] = i;
}
// Delete the last match
delete thisLeague.matchIndex[matchHash];
delete thisLeague.matches[thisLeague.matches.length - 1];
thisLeague.matches.length--;
}
/**
* Returns the match information that bears the hash generated with the user
* input parameters
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the name of the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function getMatch(
string homeTeam,
string awayTeam,
string league,
uint startTime
) view public returns(bytes32, string, string, string, uint, bool) {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
uint index = thisLeague.matchIndex[matchHash];
require(thisLeague.matches[index].hash == matchHash, "Invalid match");
Match storage retMatch = thisLeague.matches[index];
return (
retMatch.hash,
retMatch.homeTeam,
retMatch.awayTeam,
retMatch.league,
retMatch.startTime,
retMatch.finalized
);
}
/**
* Allow only arbiters for the specified 'league' to commit match results
*
* @param homeTeam the home team competing in the match
* @param awayTeam the away team competing in the match
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
* @param resultHash the hash of the result entered by the arbiter
*/
function commitMatchResult(
string homeTeam,
string awayTeam,
string league,
uint startTime,
bytes32 resultHash
) public payable {
bytes32 leagueHash = validateLeagueArbiter(msg.sender, league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// make sure match is valid
require(thisMatch.hash == matchHash, "Invalid match");
// require match is finished
require(now > startTime + 95, "Match is not finished");
// require match still needs more commits
require(
thisLeague.arbiters.length.mul(8).div(10) >= thisMatch.commits,
"Match not accepting more commits"
);
// only allow one result submission per address
require(thisMatch.resultHash[msg.sender] == 0, "Result already committed");
// must stake 'stakeAmount' to commit result
require(msg.value >= stakeAmount, "Must stake 10 Wei to commit result");
storeMatchCommit(msg.sender, league, matchHash, resultHash);
}
/**
* Allow only arbiters for the specified 'league' to reveal match results
*
* @param homeTeam the home team competing in the match
* @param awayTeam the away team competing in the match
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
* @param salt the hash added in the msg.sender's result commit
* @param homeScore the score for the home team
* @param awayScore the score for the away team
*/
function revealMatchResult(
string homeTeam,
string awayTeam,
string league,
uint startTime,
bytes32 salt,
uint homeScore,
uint awayScore
) public {
bytes32 leagueHash = validateLeagueArbiter(msg.sender, league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// make sure match is valid
require(thisMatch.hash == matchHash, "Invalid match");
// require match is finished
require(now > startTime + 95, "Match is not finished");
// require match doesn't need more commits
require(
thisLeague.arbiters.length.mul(8).div(10) < thisMatch.commits,
"Match is still accepting commits"
);
// require msg.sender committed a result
require(
thisMatch.resultHash[msg.sender] != 0,
"Result never committed or stake already withdrawn"
);
verifyMatchReveal(msg.sender, league, matchHash, salt, homeScore, awayScore);
}
/**
* Allows only match makers that submitted a correct result for a match
* withdraw a small reward taken from the bet pool for the match.
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function withdrawResult(
string homeTeam,
string awayTeam,
string league,
uint startTime
) public {
bytes32 leagueHash = validateLeagueArbiter(msg.sender, league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// require the match is finalized
require(thisMatch.finalized, "Match result is not finalized");
bytes32 finalResultHash = findFinalResultHash(homeTeam, awayTeam, league, startTime);
// require they revealed the correct result
require(
finalResultHash == thisMatch.revealHash[msg.sender],
"You did not submit the correct result"
);
// reset storage to only allow one result withdrawal
thisMatch.revealHash[msg.sender] = bytes32(0);
uint countIndex = thisMatch.resultCountIndex[finalResultHash];
Count storage resultCount = thisMatch.resultCount[countIndex];
uint winningPool;
if (resultCount.matchResult.homeTeam.score > resultCount.matchResult.awayTeam.score) {
winningPool = calculateWinningPool(league, matchHash,
resultCount.matchResult.homeTeam.name);
}
else if (resultCount.matchResult.homeTeam.score < resultCount.matchResult.awayTeam.score) {
winningPool = calculateWinningPool(league, matchHash,
resultCount.matchResult.awayTeam.name);
}
else {
//handle tie
winningPool = 0;
}
uint rewardPool = thisMatch.betPool.mul(99).div(100);
// reward if there are enough losers to guarantee winners don't lose money
if (rewardPool > winningPool) {
uint arbiterPool = thisMatch.betPool.sub(rewardPool);
uint reward = arbiterPool.div(resultCount.value);
msg.sender.transfer(reward);
}
}
/**
* Allows anyone to get the final result information for the specified
* match
*
* @param matchHash the identifying hash for the match
* @param league the league the match pertains to
*/
function getFinalResult(
bytes32 matchHash,
string league
) view public returns (bytes32, bytes32, string, uint, string, uint) {
League storage thisLeague = leagues[leagueIndex[validateLeague(league)]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// require the match is finalized
require(thisMatch.finalized, "Match result not finalized");
// loop through result counter and determine most numerous result
uint maxCounter = 0;
Result storage maxResult = thisMatch.resultCount[0].matchResult;
for (uint i = 0; i < thisMatch.resultCount.length; i++) {
if (thisMatch.resultCount[i].value > maxCounter) {
maxCounter = thisMatch.resultCount[i].value;
maxResult = thisMatch.resultCount[i].matchResult;
}
}
return (
maxResult.hash,
maxResult.matchHash,
maxResult.homeTeam.name,
maxResult.homeTeam.score,
maxResult.awayTeam.name,
maxResult.awayTeam.score
);
}
/**
* Allows anyone to place a bet on a match specified by the given
* function arguments.
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
* @param betOnTeam the team that is bet to win the match
*/
function placeBet(
string homeTeam,
string awayTeam,
string league,
uint startTime,
string betOnTeam
) payable public {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
// make sure this is a valid bet
uint index = validateBet(homeTeam, awayTeam, league,
startTime, betOnTeam);
Match storage matchBetOn = thisLeague.matches[index];
uint betIndex = matchBetOn.betterIndex[msg.sender];
if (betIndex == 0) {
// Add bet owner to ID list.
matchBetOn.betterIndex[msg.sender] = matchBetOn.bets.length;
betIndex = matchBetOn.bets.length++;
}
// Create and update storage
Bet storage b = matchBetOn.bets[betIndex];
b.matchHash = matchBetOn.hash;
b.owner = msg.sender;
b.withdrawn = false;
// place the bet on the correct team
if (keccak256(abi.encodePacked(betOnTeam)) ==
keccak256(abi.encodePacked(matchBetOn.homeTeam))) {
b.betOnTeam = homeTeam;
}
else {
b.betOnTeam = awayTeam;
}
b.amount = msg.value;
matchBetOn.betPool = matchBetOn.betPool.add(msg.value);
}
/**
* Allows anyone to remove a bet they placed on a match
*
* @notice msg.sender must have a bet placed on the match
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function removeBet(
string homeTeam,
string awayTeam,
string league,
uint startTime
) payable public {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
// make sure match is a valid match
uint index = thisLeague.matchIndex[matchHash];
require(index != 0 || thisLeague.matches[index].hash == matchHash, "Invalid match");
// require the user has placed a bet on the match
uint betIndex = thisLeague.matches[index].betterIndex[msg.sender];
require(
betIndex != 0 || thisLeague.matches[index].bets[betIndex].owner == msg.sender,
"You did not place a bet on this match"
);
// require the match hasn't started
require(now < thisLeague.matches[index].startTime, "Match already started");
// save the bet amount for refunding purposes
uint betAmount = thisLeague.matches[index].bets[betIndex].amount;
uint expectedBalance = address(this).balance.sub(betAmount);
// Rewrite the bets storage to move the 'gap' to the end.
Bet[] storage addressBets = thisLeague.matches[index].bets;
for (uint i = betIndex; i < addressBets.length - 1; i++) {
addressBets[i] = addressBets[i+1];
thisLeague.matches[index].betterIndex[addressBets[i].owner] = i;
}
// Delete the last bet
delete thisLeague.matches[index].betterIndex[msg.sender];
delete addressBets[addressBets.length-1];
addressBets.length--;
// refund and update match bet pool
thisLeague.matches[index].betPool = thisLeague.matches[index].betPool.sub(betAmount);
msg.sender.transfer(betAmount);
assert(address(this).balance == expectedBalance);
}
/**
* Allows anyone to retrieve the information about a bet they placed on
* a specified match. Information returned includes the match hash for the
* match the bet was placed on, the bet owner's address, the team bet on,
* the amount bet, and whether the bet has been withdrawn.
*
* @notice msg.sender must have a bet placed on the match
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function getBet(
string homeTeam,
string awayTeam,
string league,
uint startTime
) view public returns (bytes32, address, string, uint, bool) {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
// require the bet is on a valid match
uint index = thisLeague.matchIndex[matchHash];
require(index != 0 || thisLeague.matches[index].hash == matchHash);
// require the user has placed a bet on the match
uint betIndex = thisLeague.matches[index].betterIndex[msg.sender];
require(betIndex != 0 || thisLeague.matches[index].bets[betIndex].owner == msg.sender);
// require this is the bet owner
Bet storage userBet = thisLeague.matches[index].bets[betIndex];
require(msg.sender == userBet.owner);
return (
matchHash,
userBet.owner,
userBet.betOnTeam,
userBet.amount,
userBet.withdrawn
);
}
/**
* Allows anyone to withdraw a bet. If the bet was correct, a reward is
* calculated and transferred to the account of the msg.sender.
*
* @notice msg.sender must have a bet placed on the match
*
* @param homeTeam the home team competing in the match to be removed
* @param awayTeam the away team competing in the match to be removed
* @param league the league the match to be removed pertains to
* @param startTime the time the match to be removed begins
*/
function withdrawBet(
string homeTeam,
string awayTeam,
string league,
uint startTime
) public {
League storage thisLeague = leagues[leagueIndex[validateLeague(league)]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// require the match result is finalized
require(thisMatch.finalized, "Match result not finalized");
// require the bet hasn't been withdrawn and msg.sender owns a bet
uint betIndex = thisMatch.betterIndex[msg.sender];
Bet storage userBet = thisMatch.bets[betIndex];
require(
!userBet.withdrawn && userBet.owner == msg.sender,
"Bet already withdrawn or never placed on the match"
);
bytes32 finalResultHash = findFinalResultHash(homeTeam, awayTeam, league, startTime);
processBetWithdraw(msg.sender, league, matchHash, finalResultHash);
}
/***************************************************************************
* Private functions
**************************************************************************/
/**
* Verifies that 'leagueName' is a valid league
*/
function validateLeague(string leagueName) view private returns (bytes32) {
bytes32 leagueHash = keccak256(abi.encodePacked(leagueName));
// require it's a valid league
require(leagueIndex[leagueHash] != 0, "Invalid league");
return leagueHash;
}
/**
* Verifies that 'arbiterAddress' is a valid arbiter
*
* @notice Also verifies that 'leagueName' is a valid league
*/
function validateLeagueArbiter(
address arbiterAddress,
string leagueName
) view private returns (bytes32) {
bytes32 leagueHash = validateLeague(leagueName);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
uint index = thisLeague.arbiterIndex[arbiterAddress];
require(thisLeague.arbiters[index].id == arbiterAddress, "Invalid league arbiter");
return leagueHash;
}
/**
* Validates that a bet can be placed on a valid match
*
* @notice assumes the 'league' has already been confirmed as valid
*
* @return index the match index for the match the bet is placed on
*/
function validateBet(
string homeTeam,
string awayTeam,
string league,
uint startTime,
string betOnTeam
) view private returns (uint index) {
bytes32 leagueHash = keccak256(abi.encodePacked(league));
League storage thisLeague = leagues[leagueIndex[leagueHash]];
bytes32 matchHash = getMatchHash(homeTeam, awayTeam, league, startTime);
index = thisLeague.matchIndex[matchHash];
// require the match can still be bet on
require(thisLeague.matches[index].hash == matchHash
&& now < thisLeague.matches[index].startTime);
// require the bet is on a valid team
require(keccak256(abi.encodePacked(betOnTeam)) ==
keccak256(abi.encodePacked(thisLeague.matches[index].homeTeam))
|| keccak256(abi.encodePacked(betOnTeam)) ==
keccak256(abi.encodePacked(thisLeague.matches[index].awayTeam)));
}
/**
* Stores the result commit specified by the function parameters and
* attributes the submission to the sender address.
*
* @notice assumes the 'league' has already been confirmed as valid
* @notice assumes 'sender' has already been confirmed as a league arbiter
*
* @param sender the address that submitted this result
* @param league the league the match to be removed pertains to
* @param matchHash the unique hash that identifies the match
* @param resultHash the hash of the result committed by the arbiter
*/
function storeMatchCommit(
address sender,
string league,
bytes32 matchHash,
bytes32 resultHash
) private {
League storage thisLeague = leagues[leagueIndex[keccak256(abi.encodePacked(league))]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// map the sender's address to the hash of the result and the match hash
bytes32 resultKey = keccak256(abi.encodePacked(resultHash, matchHash));
thisMatch.resultHash[sender] = resultKey;
thisMatch.commits.add(1);
thisLeague.arbiters[thisLeague.arbiterIndex[sender]].commits.add(1);
}
/**
* Verifies that the result revealed matches the result previously committed
* by the address 'sender' for this match
*
* @notice assumes the 'league' has already been confirmed as valid
* @notice assumes 'sender' has already been confirmed as a league arbiter
*
* @param sender the address that submitted this result
* @param league the league the match to be removed pertains to
* @param matchHash the unique hash that identifies the match
* @param salt the hash added in the msg.sender's result commit
* @param homeScore the score for the home team
* @param awayScore the score for the away team
*/
function verifyMatchReveal(
address sender,
string league,
bytes32 matchHash,
bytes32 salt,
uint homeScore,
uint awayScore
) private {
League storage thisLeague = leagues[leagueIndex[keccak256(abi.encodePacked(league))]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
bytes32 commit = thisMatch.resultHash[sender];
bytes32 result = keccak256(abi.encodePacked(salt, homeScore, awayScore));
bytes32 verifyCommit = keccak256(abi.encodePacked(result, matchHash));
if (commit == verifyCommit) {
// overwrite mapping to allow only one reveal per address
thisMatch.resultHash[sender] = bytes32(0);
sender.transfer(stakeAmount);
// store the result and increase reveal number if match isn't finalized
if (!thisMatch.finalized) {
bytes32 storeResult = keccak256(abi.encodePacked(matchHash, homeScore, awayScore));
storeMatchReveal(sender, league, matchHash, storeResult, homeScore, awayScore);
}
}
}
/**
* Verifies that the result revealed matches the result previously committed
* by the address 'sender' for this match
*
* @notice assumes the 'league' has already been confirmed as valid
* @notice assumes 'sender' has already been confirmed as a league arbiter
*
* @param sender the address that submitted this result
* @param league the league the match to be removed pertains to
* @param matchHash the unique hash that identifies the match
* @param storeResult the hash to identify the result revealed
* @param homeScore the score for the home team
* @param awayScore the score for the away team
*/
function storeMatchReveal(
address sender,
string league,
bytes32 matchHash,
bytes32 storeResult,
uint homeScore,
uint awayScore
) private {
League storage thisLeague = leagues[leagueIndex[keccak256(abi.encodePacked(league))]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
// map the sender's address to the result hash
thisMatch.revealHash[sender] = storeResult;
// map the result hash to an index in the result counter array
uint countIndex = thisMatch.resultCountIndex[storeResult];
if (countIndex == 0
&& thisMatch.resultCount[countIndex].matchResult.hash != storeResult) {
// Add result to ID list
thisMatch.resultCountIndex[storeResult] = thisMatch.resultCount.length;
countIndex = thisMatch.resultCount.length++;
// identify the result
thisMatch.resultCount[countIndex].matchResult = Result(
storeResult,
matchHash,
Team(thisMatch.homeTeam, homeScore),
Team(thisMatch.awayTeam, awayScore)
);
}
// add 1 to the number of people who submitted this result
Count storage thisCount = thisMatch.resultCount[countIndex];
thisCount.value = thisCount.value.add(uint(1));
// add to the number of reveals, check if match is finalized
thisMatch.reveals.add(1);
thisLeague.arbiters[thisLeague.arbiterIndex[sender]].reveals.add(1);
if(thisMatch.commits.mul(9).div(10) < thisMatch.reveals) {
thisMatch.finalized = true;
}
}
/**
* Distributes the bet reward if the user won the bet
*
* @notice assumes the 'league' has already been confirmed as valid
*
* @param sender the address that submitted a bet on this match
* @param league the league the match to be removed pertains to
* @param matchHash the unique hash that identifies the match
* @param finalResultHash the hash of the finalized match result
*/
function processBetWithdraw(
address sender,
string league,
bytes32 matchHash,
bytes32 finalResultHash
) private {
League storage thisLeague = leagues[leagueIndex[validateLeague(league)]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
uint resultIndex = thisMatch.resultCountIndex[finalResultHash];
Result storage finalResult = thisMatch.resultCount[resultIndex].matchResult;
uint betIndex = thisMatch.betterIndex[msg.sender];
Bet storage userBet = thisMatch.bets[betIndex];
// withdraw Bet
userBet.withdrawn = true;
uint reward;
if (finalResult.homeTeam.score == finalResult.awayTeam.score) {
// handle tie
reward = userBet.amount.mul(99).div(100);
sender.transfer(reward);
}
else {
// handle win
uint winningPool;
uint rewardPool = thisMatch.betPool.mul(99).div(100);
if (finalResult.homeTeam.score > finalResult.awayTeam.score) {
if (keccak256(abi.encodePacked(userBet.betOnTeam))
== keccak256(abi.encodePacked(finalResult.homeTeam.name))) {
winningPool = calculateWinningPool(league, matchHash,
finalResult.homeTeam.name);
reward = rewardPool.mul(userBet.amount).div(winningPool);
sender.transfer(reward);
}
}
else {
if (keccak256(abi.encodePacked(userBet.betOnTeam))
== keccak256(abi.encodePacked(finalResult.awayTeam.name))) {
winningPool = calculateWinningPool(league, matchHash,
finalResult.awayTeam.name);
reward = rewardPool.mul(userBet.amount).div(winningPool);
sender.transfer(reward);
}
}
}
}
/**
* Returns the hash of the final result for the specified match
*/
function findFinalResultHash(
string homeTeam,
string awayTeam,
string league,
uint startTime
) view private returns (bytes32) {
(bytes32 resultHash,
bytes32 matchHash,
string memory homeName,
uint homeScore,
string memory awayName,
uint awayScore) = getFinalResult(
getMatchHash(homeTeam, awayTeam, league, startTime),
league
);
return resultHash;
}
/**
* Calculates and returns the sum of the correct bet amounts
*
* @param matchHash the hash of the match the bets are for
* @param league the league the match pertains to
* @param winningTeam the team that won the match
*/
function calculateWinningPool(
string league,
bytes32 matchHash,
string winningTeam
) view private returns (uint winningPool) {
bytes32 leagueHash = validateLeague(league);
League storage thisLeague = leagues[leagueIndex[leagueHash]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
winningPool = 0;
for (uint i = 0; i < thisMatch.bets.length; i++) {
Bet storage thisBet = thisMatch.bets[i];
if (keccak256(abi.encodePacked(thisBet.betOnTeam))
== keccak256(abi.encodePacked(winningTeam))) {
winningPool = winningPool.add(thisBet.amount);
}
}
}
/**
* Calculates the unique byte32 identifier hash for the specified match
*/
function getMatchHash(
string homeTeam,
string awayTeam,
string league,
uint startTime
) pure private returns (bytes32 matchHash){
matchHash = keccak256(abi.encodePacked(
homeTeam,
awayTeam,
league,
startTime
));
}
}
/**
* @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;
}
}
|
Allows anyone to get the final result information for the specified match matchHash the identifying hash for the match league the league the match pertains to/ require the match is finalized loop through result counter and determine most numerous result
|
function getFinalResult(
bytes32 matchHash,
string league
) view public returns (bytes32, bytes32, string, uint, string, uint) {
League storage thisLeague = leagues[leagueIndex[validateLeague(league)]];
Match storage thisMatch = thisLeague.matches[thisLeague.matchIndex[matchHash]];
require(thisMatch.finalized, "Match result not finalized");
uint maxCounter = 0;
Result storage maxResult = thisMatch.resultCount[0].matchResult;
for (uint i = 0; i < thisMatch.resultCount.length; i++) {
if (thisMatch.resultCount[i].value > maxCounter) {
maxCounter = thisMatch.resultCount[i].value;
maxResult = thisMatch.resultCount[i].matchResult;
}
}
return (
maxResult.hash,
maxResult.matchHash,
maxResult.homeTeam.name,
maxResult.homeTeam.score,
maxResult.awayTeam.name,
maxResult.awayTeam.score
);
}
| 12,535,203
|
/**
*Submitted for verification at Etherscan.io on 2022-04-29
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IVault {
function token() external view returns (address);
}
interface IRegistry {
function numVaults(address) external view returns (uint256);
function vaults(address, uint256) external view returns (address);
}
interface IAddressesProvider {
function addressById(string memory) external view returns (address);
}
interface IRegistryAdapter {
function registryAddress() external view returns (address);
}
contract AllowlistImplementationPartnerTracker {
address constant public partnerTracker = 0x8ee392a4787397126C163Cb9844d7c447da419D8;
address public addressesProviderAddress;
constructor(address _addressesProviderAddress) {
addressesProviderAddress = _addressesProviderAddress;
}
/**
* @notice Determine whether the address is yearn's deployed partner tracker contract
* @param _address the address to validate
* @return returns true if the input is the partner tracker
*/
function isPartnerTracker(address _address) external view returns (bool) {
return _address == partnerTracker;
}
/**
* @notice Determine whether or not a vault address is a valid vault
* @param vaultAddress The vault address to test
* @return Returns true if the valid address is valid and false if not
*/
function isVault(address vaultAddress) public view returns (bool) {
IVault vault = IVault(vaultAddress);
address tokenAddress;
try vault.token() returns (address _tokenAddress) {
tokenAddress = _tokenAddress;
} catch {
return false;
}
uint256 numVaults = registry().numVaults(tokenAddress);
for (uint256 vaultIdx; vaultIdx < numVaults; vaultIdx++) {
address currentVaultAddress = registry().vaults(tokenAddress, vaultIdx);
if (currentVaultAddress == vaultAddress) {
return true;
}
}
return false;
}
/**
* @dev Fetch registry adapter address
*/
function registryAdapterAddress() public view returns (address) {
return
IAddressesProvider(addressesProviderAddress).addressById(
"REGISTRY_ADAPTER_V2_VAULTS"
);
}
/**
* @dev Fetch registry adapter interface
*/
function registryAdapter() internal view returns (IRegistryAdapter) {
return IRegistryAdapter(registryAdapterAddress());
}
/**
* @dev Fetch registry address
*/
function registryAddress() public view returns (address) {
return registryAdapter().registryAddress();
}
/**
* @dev Fetch registry interface
*/
function registry() internal view returns (IRegistry) {
return IRegistry(registryAddress());
}
}
|
Fetch registry adapter address/
|
function registryAdapterAddress() public view returns (address) {
return
IAddressesProvider(addressesProviderAddress).addressById(
"REGISTRY_ADAPTER_V2_VAULTS"
);
}
| 15,392,231
|
./full_match/1/0x4669159013301f8B0e0bF43077f4263E244101BC/sources/contracts/AvoFactory.sol
|
deploys a AvoSafe deterministically for owner_ owner_ AvoSafe owner return deployedAvoSafe_ the deployed contract address deploy AvoSafe using CREATE2 opcode (through specifying salt) initialize AvoWallet through proxy with IAvoWallet interface
|
function _deployAvoSafeDeterministic(address owner_) internal returns (address deployedAvoSafe_) {
IAvoWallet(deployedAvoSafe_).initialize(owner_);
emit AvoSafeDeployed(owner_, deployedAvoSafe_);
}
| 9,774,914
|
pragma solidity ^0.4.8;
import "./Ownable.sol";
import "../token/ERC20Basic.sol";
/// @title Contracts that should not own Tokens
/// @author Remco Bloemen <remco@2ฯ.com>
///
/// This blocks incoming ERC23 tokens to prevent accidental
/// loss of tokens. Should tokens (any ERC20Basic compatible)
/// end up in the contract, it allows the owner to reclaim
/// the tokens.
contract HasNoTokens is Ownable {
/// Reject all ERC23 compatible tokens
function tokenFallback(address from_, uint value_, bytes data_) external {
throw;
}
/// Reclaim all ERC20Basic compatible tokens
function reclaimToken(address tokenAddr) external onlyOwner {
ERC20Basic tokenInst = ERC20Basic(tokenAddr);
uint256 balance = tokenInst.balanceOf(this);
tokenInst.transfer(owner, balance);
}
}
|
Reject all ERC23 compatible tokens
|
function tokenFallback(address from_, uint value_, bytes data_) external {
throw;
}
| 905,525
|
pragma solidity ^0.5.0;
// Copyright 2019 OpenST Ltd.
//
// 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.
import "./EIP20Token.sol";
import "./Organized.sol";
import "./SafeMath.sol";
/**
* @title Branded Token.
*
* @notice Branded tokens are minted by staking specified value tokens.
*/
contract BrandedToken is Organized, EIP20Token {
/* Usings */
using SafeMath for uint256;
/* Events */
event StakeRequested(
bytes32 indexed _stakeRequestHash,
address _staker,
uint256 _stake,
uint256 _nonce
);
event StakeRequestAccepted(
bytes32 indexed _stakeRequestHash,
address _staker,
uint256 _stake
);
event StakeRequestRevoked(
bytes32 indexed _stakeRequestHash,
address _staker,
uint256 _stake
);
event Redeemed(
address _redeemer,
uint256 _valueTokens
);
event StakeRequestRejected(
bytes32 indexed _stakeRequestHash,
address _staker,
uint256 _stake
);
event SymbolSet(string _symbol);
event NameSet(string _name);
/* Structs */
struct StakeRequest {
address staker;
uint256 stake;
uint256 nonce;
}
/* Storage */
/** Address for value tokens staked to mint branded tokens. */
EIP20Interface public valueToken;
/** Conversion rate from value tokens to branded tokens. */
uint256 public conversionRate;
/** Number of digits to the right of the decimal point in conversionRate. */
uint8 public conversionRateDecimals;
/** Global nonce for stake requests. */
uint256 public nonce;
/** Flag indicating whether restrictions have been lifted for all actors. */
bool public allRestrictionsLifted;
/** Domain separator encoding per EIP 712. */
bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(address verifyingContract)"
);
/** StakeRequest struct type encoding per EIP 712. */
bytes32 private constant BT_STAKE_REQUEST_TYPEHASH = keccak256(
"StakeRequest(address staker,uint256 stake,uint256 nonce)"
);
/** Domain separator per EIP 712. */
bytes32 private DOMAIN_SEPARATOR = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
address(this)
)
);
/** Maps staker to stakeRequestHashes. */
mapping(address => bytes32) public stakeRequestHashes;
/** Maps stakeRequestHash to StakeRequests. */
mapping(bytes32 => StakeRequest) public stakeRequests;
/** Maps actor to restriction status. */
mapping(address => bool) private unrestricted;
/* Modifiers */
modifier onlyUnrestricted {
require(
allRestrictionsLifted || unrestricted[msg.sender],
"Msg.sender is restricted."
);
_;
}
/* Constructor */
/**
* @dev Conversion parameters provide the conversion rate and its scale.
* For example, if 1 value token is equivalent to 3.5 branded
* tokens (1:3.5), _conversionRate == 35 and
* _conversionRateDecimals == 1.
*
* Constructor requires:
* - valueToken address is not zero
* - conversionRate is not zero
* - conversionRateDecimals is not greater than 5
*
* @param _valueToken The value to which valueToken is set.
* @param _symbol The value to which tokenSymbol, defined in EIP20Token,
* is set.
* @param _name The value to which tokenName, defined in EIP20Token,
* is set.
* @param _decimals The value to which tokenDecimals, defined in EIP20Token,
* is set.
* @param _conversionRate The value to which conversionRate is set.
* @param _conversionRateDecimals The value to which
* conversionRateDecimals is set.
* @param _organization The value to which organization, defined in Organized,
* is set.
*/
constructor(
EIP20Interface _valueToken,
string memory _symbol,
string memory _name,
uint8 _decimals,
uint256 _conversionRate,
uint8 _conversionRateDecimals,
OrganizationInterface _organization
)
EIP20Token(_symbol, _name, _decimals)
Organized(_organization)
public
{
require(
address(_valueToken) != address(0),
"ValueToken is zero."
);
require(
_conversionRate != 0,
"ConversionRate is zero."
);
require(
_conversionRateDecimals <= 5,
"ConversionRateDecimals is greater than 5."
);
valueToken = _valueToken;
conversionRate = _conversionRate;
conversionRateDecimals = _conversionRateDecimals;
}
/* External Functions */
/**
* @notice Transfers value tokens from msg.sender to itself,
* stores the amount of branded tokens to mint if request
* is accepted, and emits stake request information.
*
* @dev It is expected that this contract will have a sufficientallowance
* to transfer value tokens from the staker at the time this function
* is executed.
*
* Function requires:
* - _mint is equivalent to _stake
* - msg.sender does not have a stake request hash
* - valueToken.transferFrom returns true
*
* @param _stake Amount of value tokens to stake.
* @param _mint Amount of branded tokens to mint.
*
* @return stakeRequestHash_ Hash of stake request information calculated per
* EIP 712.
*/
function requestStake(
uint256 _stake,
uint256 _mint
)
external
returns (bytes32 stakeRequestHash_)
{
require(
_mint == convertToBrandedTokens(_stake),
"Mint is not equivalent to stake."
);
require(
stakeRequestHashes[msg.sender] == "",
"Staker has a stake request hash."
);
StakeRequest memory stakeRequest = StakeRequest({
staker: msg.sender,
stake: _stake,
nonce: nonce
});
// Calculates hash per EIP 712
stakeRequestHash_ = hash(stakeRequest);
stakeRequestHashes[msg.sender] = stakeRequestHash_;
stakeRequests[stakeRequestHash_] = stakeRequest;
nonce += 1;
emit StakeRequested(
stakeRequestHash_,
stakeRequest.staker,
stakeRequest.stake,
stakeRequest.nonce
);
require(
valueToken.transferFrom(msg.sender, address(this), _stake),
"ValueToken.transferFrom returned false."
);
}
/**
* @notice Mints and transfers branded tokens to a staker,
* increases the total token supply, and
* emits stake request acceptance and transfer information.
*
* @dev The function has no access controls, but will only accept
* the signature of a worker, as defined in Organization.
*
* Function requires:
* - stake request exists
* - signature is from a worker
*
* @param _stakeRequestHash Stake request hash.
* @param _r R of the signature.
* @param _s S of the signature.
* @param _v V of the signature.
*
* @return success_ True.
*/
function acceptStakeRequest(
bytes32 _stakeRequestHash,
bytes32 _r,
bytes32 _s,
uint8 _v
)
external
returns (bool success_)
{
require(
stakeRequests[_stakeRequestHash].staker != address(0),
"Stake request not found."
);
StakeRequest storage stakeRequest = stakeRequests[_stakeRequestHash];
require(
verifySigner(stakeRequest, _r, _s, _v),
"Signer is not a worker."
);
emit StakeRequestAccepted(
_stakeRequestHash,
stakeRequest.staker,
stakeRequest.stake
);
uint256 mint = convertToBrandedTokens(stakeRequest.stake);
balances[stakeRequest.staker] = balances[stakeRequest.staker]
.add(mint);
totalTokenSupply = totalTokenSupply.add(mint);
// Mint branded tokens
emit Transfer(address(0), stakeRequest.staker, mint);
delete stakeRequestHashes[stakeRequest.staker];
delete stakeRequests[_stakeRequestHash];
return true;
}
/**
* @notice Maps addresses in _restrictionLifted to true in unrestricted.
*
* @dev Function requires:
* - msg.sender is a worker
*
* @param _restrictionLifted Addresses for which to lift restrictions.
*
* @return success_ True.
*/
function liftRestriction(
address[] calldata _restrictionLifted
)
external
onlyWorker
returns (bool success_)
{
for (uint256 i = 0; i < _restrictionLifted.length; i++) {
unrestricted[_restrictionLifted[i]] = true;
}
return true;
}
/**
* @notice Indicates whether an actor is unrestricted.
*
* @param _actor Actor.
*
* @return isUnrestricted_ Whether unrestricted.
*/
function isUnrestricted(address _actor)
external
view
returns (bool isUnrestricted_)
{
return unrestricted[_actor];
}
/**
* @notice Lifts restrictions from all actors.
*
* @dev Function requires:
* - msg.sender is organization
*
* @return success_ True.
*/
function liftAllRestrictions()
external
onlyOrganization
returns (bool success_)
{
allRestrictionsLifted = true;
return true;
}
/**
* @notice Revokes stake request by deleting its information and
* transferring staked value tokens back to staker.
*
* @dev Function requires:
* - msg.sender is staker
* - valueToken.transfer returns true
*
* @param _stakeRequestHash Stake request hash.
*
* @return success_ True.
*/
function revokeStakeRequest(
bytes32 _stakeRequestHash
)
external
returns (bool success_)
{
require(
stakeRequests[_stakeRequestHash].staker == msg.sender,
"Msg.sender is not staker."
);
uint256 stake = stakeRequests[_stakeRequestHash].stake;
delete stakeRequestHashes[msg.sender];
delete stakeRequests[_stakeRequestHash];
emit StakeRequestRevoked(
_stakeRequestHash,
msg.sender,
stake
);
require(
valueToken.transfer(msg.sender, stake),
"ValueToken.transfer returned false."
);
return true;
}
/**
* @notice Reduces msg.sender's balance and the total supply by
* _brandedTokens and transfers an equivalent amount of
* value tokens to msg.sender.
*
* @dev Redemption may risk loss of branded tokens.
* It is possible to redeem branded tokens for 0 value tokens.
*
* Function requires:
* - valueToken.transfer returns true
*
* @param _brandedTokens Amount of branded tokens to redeem.
*
* @return success_ True.
*/
function redeem(
uint256 _brandedTokens
)
external
returns (bool success_)
{
balances[msg.sender] = balances[msg.sender].sub(_brandedTokens);
totalTokenSupply = totalTokenSupply.sub(_brandedTokens);
uint256 valueTokens = convertToValueTokens(_brandedTokens);
emit Redeemed(msg.sender, valueTokens);
// Burn redeemed branded tokens
emit Transfer(msg.sender, address(0), _brandedTokens);
require(
valueToken.transfer(msg.sender, valueTokens),
"ValueToken.transfer returned false."
);
return true;
}
/**
* @notice Rejects stake request by deleting its information and
* transferring staked value tokens back to staker.
*
* @dev Function requires:
* - msg.sender is a worker
* - stake request exists
* - valueToken.transfer returns true
*
* @param _stakeRequestHash Stake request hash.
*
* @return success_ True.
*/
function rejectStakeRequest(
bytes32 _stakeRequestHash
)
external
onlyWorker
returns (bool success_)
{
require(
stakeRequests[_stakeRequestHash].staker != address(0),
"Stake request not found."
);
StakeRequest memory stakeRequest = stakeRequests[_stakeRequestHash];
delete stakeRequestHashes[stakeRequest.staker];
delete stakeRequests[_stakeRequestHash];
emit StakeRequestRejected(
_stakeRequestHash,
stakeRequest.staker,
stakeRequest.stake
);
require(
valueToken.transfer(stakeRequest.staker, stakeRequest.stake),
"ValueToken.transfer returned false."
);
return true;
}
/**
* @notice Sets symbol.
*
* @dev Function requires:
* - msg.sender is a worker
*
* @param _symbol The value to which symbol is set.
*
* @return success_ True.
*/
function setSymbol(
string calldata _symbol
)
external
onlyWorker
returns (bool success_)
{
tokenSymbol = _symbol;
emit SymbolSet(tokenSymbol);
return true;
}
/**
* @notice Sets name.
*
* @dev Function requires:
* - msg.sender is a worker
*
* @param _name The value to which name is set.
*
* @return success_ True.
*/
function setName(
string calldata _name
)
external
onlyWorker
returns (bool success_)
{
tokenName = _name;
emit NameSet(tokenName);
return true;
}
/* Public Functions */
/**
* @notice Overrides EIP20Token.transfer by additionally
* requiring msg.sender to be unrestricted.
*
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens to be transferred.
*
* @return success_ Result from EIP20Token transfer.
*/
function transfer(
address _to,
uint256 _value
)
public
onlyUnrestricted
returns (bool success_)
{
return super.transfer(_to, _value);
}
/**
* @notice Overrides EIP20Token.transferFrom by additionally
* requiring msg.sender to be unrestricted.
*
* @param _from Address from which tokens are transferred.
* @param _to Address to which tokens are transferred.
* @param _value Amount of tokens transferred.
*
* @return success_ Result from EIP20Token transferFrom.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
onlyUnrestricted
returns (bool success_)
{
return super.transferFrom(_from, _to, _value);
}
/**
* @notice Returns the amount of branded tokens equivalent to a
* given amount of value tokens.
*
* @dev Please note there may be a loss of up to 1 indivisible unit of
* this token (i.e., assuming 1 value token is equivalent
* to 3.5 branded tokens, convert(1) --> 3, not 3.5).
*
* @param _valueTokens Amount to convert.
*
* @return uint256 Converted amount.
*/
function convertToBrandedTokens(
uint256 _valueTokens
)
public
view
returns (uint256)
{
return (
_valueTokens
.mul(conversionRate)
.div(10 ** uint256(conversionRateDecimals))
);
}
/**
* @notice Returns the amount of value tokens equivalent to a
* given amount of branded tokens.
*
* @dev Please note there may be a loss of up to 1 indivisible unit of
* this token.
*
* @param _brandedTokens Amount to convert.
*
* @return uint256 Converted amount.
*/
function convertToValueTokens(
uint256 _brandedTokens
)
public
view
returns (uint256)
{
return (
_brandedTokens
.mul(10 ** uint256(conversionRateDecimals))
.div(conversionRate)
);
}
/* Private Functions */
/**
* @notice Calculates stakeRequestHash according to EIP 712.
*
* @param _stakeRequest StakeRequest instance to hash.
*
* @return bytes32 EIP 712 hash of _stakeRequest.
*/
function hash(
StakeRequest memory _stakeRequest
)
private
pure
returns (bytes32)
{
return keccak256(
abi.encode(
BT_STAKE_REQUEST_TYPEHASH,
_stakeRequest.staker,
_stakeRequest.stake,
_stakeRequest.nonce
)
);
}
/**
* @notice Verifies whether signer of stakeRequestHash is a worker.
*
* @dev Signing the stakeRequestHash consistent with eth_signTypedData,
* as specified by EIP 712, requires signing a hash of encoded data
* comprising:
* - an initial byte
* - the version byte for structured data
* - the domain separator
* - the stakeRequestHash
*
* See: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md
*
* @param _stakeRequest Stake request.
* @param _r R of the signature.
* @param _s S of the signature.
* @param _v V of the signature.
*
* @return bool True if signer is a worker, false if not.
*/
function verifySigner(
StakeRequest storage _stakeRequest,
bytes32 _r,
bytes32 _s,
uint8 _v
)
private
view
returns (bool)
{
// See: https://github.com/ethereum/EIPs/blob/master/assets/eip-712/Example.sol
bytes32 typedData = keccak256(
abi.encodePacked(
byte(0x19), // the initial 0x19 byte
byte(0x01), // the version byte for structured data
DOMAIN_SEPARATOR,
hash(_stakeRequest)
)
);
return organization.isWorker(ecrecover(typedData, _v, _r, _s));
}
}
|
Indicates whether an actor is unrestricted. _actor Actor. return isUnrestricted_ Whether unrestricted./
|
function isUnrestricted(address _actor)
external
view
returns (bool isUnrestricted_)
{
return unrestricted[_actor];
}
| 2,504,321
|
./full_match/80001/0x263Dc586cFcEd78cB2838a23B2B5a4E57B72fabA/sources/src/RealEstate.sol
|
for (uint256 i; i < propertyIndex; ++i){ if(properties[i+1].owner == user){ itemCount++; } }
|
function getUserProperties(
address user
) external view returns (Property[] memory) {
Property[] memory userProperties;
for (uint i; i < propertyIndex; ++i) {
if (properties[i + 1].owner == user) {
userProperties[i] = properties[i + 1];
}
}
return userProperties;
}
| 5,695,285
|
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
/**
* @title 1Inch(On-chain).
* @dev On-chain and off-chian DEX Aggregator.
*/
import { TokenInterface , MemoryInterface } from "../../common/interfaces.sol";
import { Stores } from "../../common/stores.sol";
import { OneProtoInterface, OneProtoData, OneProtoMultiData } from "./interface.sol";
import { Helpers } from "./helpers.sol";
import { Events } from "./events.sol";
abstract contract OneProtoResolver is Helpers, Events {
/**
* @dev 1proto contract swap handler
* @param oneProtoData - Struct with swap data defined in interfaces.sol
*/
function oneProtoSwap(
OneProtoData memory oneProtoData
) internal returns (uint buyAmt) {
TokenInterface _sellAddr = oneProtoData.sellToken;
TokenInterface _buyAddr = oneProtoData.buyToken;
uint _sellAmt = oneProtoData._sellAmt;
uint _slippageAmt = getSlippageAmt(_buyAddr, _sellAddr, _sellAmt, oneProtoData.unitAmt);
uint ethAmt;
if (address(_sellAddr) == ethAddr) {
ethAmt = _sellAmt;
} else {
approve(_sellAddr, address(oneProto), _sellAmt);
}
uint initalBal = getTokenBal(_buyAddr);
oneProto.swap{value: ethAmt}(
_sellAddr,
_buyAddr,
_sellAmt,
_slippageAmt,
oneProtoData.distribution,
oneProtoData.disableDexes
);
uint finalBal = getTokenBal(_buyAddr);
buyAmt = sub(finalBal, initalBal);
require(_slippageAmt <= buyAmt, "Too much slippage");
}
/**
* @dev 1proto contract multi swap handler
* @param oneProtoData - Struct with multiple swap data defined in interfaces.sol
*/
function oneProtoSwapMulti(OneProtoMultiData memory oneProtoData) internal returns (uint buyAmt) {
TokenInterface _sellAddr = oneProtoData.sellToken;
TokenInterface _buyAddr = oneProtoData.buyToken;
uint _sellAmt = oneProtoData._sellAmt;
uint _slippageAmt = getSlippageAmt(_buyAddr, _sellAddr, _sellAmt, oneProtoData.unitAmt);
uint ethAmt;
if (address(_sellAddr) == ethAddr) {
ethAmt = _sellAmt;
} else {
approve(_sellAddr, address(oneProto), _sellAmt);
}
uint initalBal = getTokenBal(_buyAddr);
oneProto.swapMulti{value: ethAmt}(
convertToTokenInterface(oneProtoData.tokens),
_sellAmt,
_slippageAmt,
oneProtoData.distribution,
oneProtoData.disableDexes
);
uint finalBal = getTokenBal(_buyAddr);
buyAmt = sub(finalBal, initalBal);
require(_slippageAmt <= buyAmt, "Too much slippage");
}
}
abstract contract OneProtoResolverHelpers is OneProtoResolver {
/**
* @dev Gets the swapping data offchian for swaps and calls swap.
* @param oneProtoData - Struct with swap data defined in interfaces.sol
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function _sell(
OneProtoData memory oneProtoData,
uint getId,
uint setId
) internal returns (OneProtoData memory) {
uint _sellAmt = getUint(getId, oneProtoData._sellAmt);
oneProtoData._sellAmt = _sellAmt == uint(-1) ?
getTokenBal(oneProtoData.sellToken) :
_sellAmt;
oneProtoData._buyAmt = oneProtoSwap(oneProtoData);
setUint(setId, oneProtoData._buyAmt);
return oneProtoData;
}
/**
* @dev Gets the swapping data offchian for swaps and calls swap.
* @param oneProtoData - Struct with multiple swap data defined in interfaces.sol
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function _sellMulti(
OneProtoMultiData memory oneProtoData,
uint getId,
uint setId
) internal returns (OneProtoMultiData memory) {
uint _sellAmt = getUint(getId, oneProtoData._sellAmt);
oneProtoData._sellAmt = _sellAmt == uint(-1) ?
getTokenBal(oneProtoData.sellToken) :
_sellAmt;
oneProtoData._buyAmt = oneProtoSwapMulti(oneProtoData);
setUint(setId, oneProtoData._buyAmt);
// emitLogSellMulti(oneProtoData, getId, setId);
return oneProtoData;
}
}
abstract contract OneProto is OneProtoResolverHelpers {
/**
* @dev Sell ETH/ERC20_Token using 1Proto using off-chain calculation.
* @notice Swap tokens from exchanges like Uniswap, Kyber etc, with calculation done off-chain.
* @param buyAddr The address of the token to buy.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param sellAddr The address of the token to sell.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param sellAmt The amount of the token to sell.
* @param unitAmt The amount of buyAmt/sellAmt with slippage.
* @param distribution The distribution of swap across different DEXs.
* @param disableDexes Disable a dex. (To disable none: 0)
* @param getId ID to retrieve sellAmt.
* @param setId ID stores the amount of token brought.
*/
function sell(
address buyAddr,
address sellAddr,
uint sellAmt,
uint unitAmt,
uint[] calldata distribution,
uint disableDexes,
uint getId,
uint setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
OneProtoData memory oneProtoData = OneProtoData({
buyToken: TokenInterface(buyAddr),
sellToken: TokenInterface(sellAddr),
_sellAmt: sellAmt,
unitAmt: unitAmt,
distribution: distribution,
disableDexes: disableDexes,
_buyAmt: 0
});
oneProtoData = _sell(oneProtoData, getId, setId);
_eventName = "LogSell(address,address,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(buyAddr, sellAddr, oneProtoData._buyAmt, oneProtoData._sellAmt, getId, setId);
}
/**
* @dev Sell Multiple tokens using 1proto using off-chain calculation.
* @notice Swap multiple tokens from exchanges like Uniswap, Kyber etc, with calculation done off-chain.
* @param tokens Array of tokens.
* @param sellAmt The amount of the token to sell.
* @param unitAmt The amount of buyAmt/sellAmt with slippage.
* @param distribution The distribution of swap across different DEXs.
* @param disableDexes Disable a dex. (To disable none: 0)
* @param getId ID to retrieve sellAmt.
* @param setId ID stores the amount of token brought.
*/
function sellMulti(
address[] calldata tokens,
uint sellAmt,
uint unitAmt,
uint[] calldata distribution,
uint[] calldata disableDexes,
uint getId,
uint setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
uint _length = tokens.length;
OneProtoMultiData memory oneProtoData = OneProtoMultiData({
tokens: tokens,
buyToken: TokenInterface(address(tokens[_length - 1])),
sellToken: TokenInterface(address(tokens[0])),
unitAmt: unitAmt,
distribution: distribution,
disableDexes: disableDexes,
_sellAmt: sellAmt,
_buyAmt: 0
});
oneProtoData = _sellMulti(oneProtoData, getId, setId);
_eventName = "LogSellMulti(address[],address,address,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(
tokens,
address(oneProtoData.buyToken),
address(oneProtoData.sellToken),
oneProtoData._buyAmt,
oneProtoData._sellAmt,
getId,
setId
);
}
}
contract ConnectV2OneProto is OneProto {
string public name = "1Proto-v1.1";
}
pragma solidity ^0.7.0;
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint) external;
function transferFrom(address, address, uint) external;
function deposit() external payable;
function withdraw(uint) external;
function balanceOf(address) external view returns (uint);
function decimals() external view returns (uint);
}
interface MemoryInterface {
function getUint(uint id) external returns (uint num);
function setUint(uint id, uint val) external;
}
interface InstaMapping {
function cTokenMapping(address) external view returns (address);
function gemJoinMapping(bytes32) external view returns (address);
}
interface AccountInterface {
function enable(address) external;
function disable(address) external;
function isAuth(address) external view returns (bool);
}
pragma solidity ^0.7.0;
import { MemoryInterface, InstaMapping } from "./interfaces.sol";
abstract contract Stores {
/**
* @dev Return ethereum address
*/
address constant internal ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/**
* @dev Return Wrapped ETH address
*/
address constant internal wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/**
* @dev Return memory variable address
*/
MemoryInterface constant internal instaMemory = MemoryInterface(0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F);
/**
* @dev Return InstaDApp Mapping Addresses
*/
InstaMapping constant internal instaMapping = InstaMapping(0xe81F70Cc7C0D46e12d70efc60607F16bbD617E88);
/**
* @dev Get Uint value from InstaMemory Contract.
*/
function getUint(uint getId, uint val) internal returns (uint returnVal) {
returnVal = getId == 0 ? val : instaMemory.getUint(getId);
}
/**
* @dev Set Uint value in InstaMemory Contract.
*/
function setUint(uint setId, uint val) virtual internal {
if (setId != 0) instaMemory.setUint(setId, val);
}
}
pragma solidity ^0.7.0;
import { TokenInterface } from "../../common/interfaces.sol";
interface OneProtoInterface {
function swap(
TokenInterface fromToken,
TokenInterface destToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 flags // See contants in IOneSplit.sol
) external payable returns(uint256);
function swapMulti(
TokenInterface[] calldata tokens,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256[] calldata flags
) external payable returns(uint256 returnAmount);
function getExpectedReturn(
TokenInterface fromToken,
TokenInterface destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
external
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
interface OneProtoMappingInterface {
function oneProtoAddress() external view returns(address);
}
struct OneProtoData {
TokenInterface sellToken;
TokenInterface buyToken;
uint _sellAmt;
uint _buyAmt;
uint unitAmt;
uint[] distribution;
uint disableDexes;
}
struct OneProtoMultiData {
address[] tokens;
TokenInterface sellToken;
TokenInterface buyToken;
uint _sellAmt;
uint _buyAmt;
uint unitAmt;
uint[] distribution;
uint[] disableDexes;
}
pragma solidity ^0.7.0;
import { TokenInterface } from "../../common/interfaces.sol";
import { DSMath } from "../../common/math.sol";
import { Basic } from "../../common/basic.sol";
import { TokenInterface, OneProtoInterface } from "./interface.sol";
abstract contract Helpers is DSMath, Basic {
/**
* @dev 1proto Address
*/
OneProtoInterface constant internal oneProto = OneProtoInterface(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e);
function getSlippageAmt(
TokenInterface _buyAddr,
TokenInterface _sellAddr,
uint _sellAmt,
uint unitAmt
) internal view returns(uint _slippageAmt) {
(uint _buyDec, uint _sellDec) = getTokensDec(_buyAddr, _sellAddr);
uint _sellAmt18 = convertTo18(_sellDec, _sellAmt);
_slippageAmt = convert18ToDec(_buyDec, wmul(unitAmt, _sellAmt18));
}
function convertToTokenInterface(address[] memory tokens) internal pure returns(TokenInterface[] memory) {
TokenInterface[] memory _tokens = new TokenInterface[](tokens.length);
for (uint i = 0; i < tokens.length; i++) {
_tokens[i] = TokenInterface(tokens[i]);
}
return _tokens;
}
}
pragma solidity ^0.7.0;
contract Events {
event LogSell(
address indexed buyToken,
address indexed sellToken,
uint256 buyAmt,
uint256 sellAmt,
uint256 getId,
uint256 setId
);
event LogSellMulti(
address[] tokens,
address indexed buyToken,
address indexed sellToken,
uint256 buyAmt,
uint256 sellAmt,
uint256 getId,
uint256 setId
);
}
pragma solidity ^0.7.0;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
contract DSMath {
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(x, y);
}
function sub(uint x, uint y) internal virtual pure returns (uint z) {
z = SafeMath.sub(x, y);
}
function mul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.mul(x, y);
}
function div(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.div(x, y);
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, RAY), y / 2) / y;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, y), RAY / 2) / RAY;
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
function toRad(uint wad) internal pure returns (uint rad) {
rad = mul(wad, 10 ** 27);
}
}
pragma solidity ^0.7.0;
import { TokenInterface } from "./interfaces.sol";
import { Stores } from "./stores.sol";
import { DSMath } from "./math.sol";
abstract contract Basic is DSMath, Stores {
function convert18ToDec(uint _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = (_amt / 10 ** (18 - _dec));
}
function convertTo18(uint _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = mul(_amt, 10 ** (18 - _dec));
}
function getTokenBal(TokenInterface token) internal view returns(uint _amt) {
_amt = address(token) == ethAddr ? address(this).balance : token.balanceOf(address(this));
}
function getTokensDec(TokenInterface buyAddr, TokenInterface sellAddr) internal view returns(uint buyDec, uint sellDec) {
buyDec = address(buyAddr) == ethAddr ? 18 : buyAddr.decimals();
sellDec = address(sellAddr) == ethAddr ? 18 : sellAddr.decimals();
}
function encodeEvent(string memory eventName, bytes memory eventParam) internal pure returns (bytes memory) {
return abi.encode(eventName, eventParam);
}
function approve(TokenInterface token, address spender, uint256 amount) internal {
try token.approve(spender, amount) {
} catch {
token.approve(spender, 0);
token.approve(spender, amount);
}
}
function changeEthAddress(address buy, address sell) internal pure returns(TokenInterface _buy, TokenInterface _sell){
_buy = buy == ethAddr ? TokenInterface(wethAddr) : TokenInterface(buy);
_sell = sell == ethAddr ? TokenInterface(wethAddr) : TokenInterface(sell);
}
function convertEthToWeth(bool isEth, TokenInterface token, uint amount) internal {
if(isEth) token.deposit{value: amount}();
}
function convertWethToEth(bool isEth, TokenInterface token, uint amount) internal {
if(isEth) {
approve(token, address(token), amount);
token.withdraw(amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
|
Gets the swapping data offchian for swaps and calls swap. oneProtoData - Struct with multiple swap data defined in interfaces.sol getId Get token amount at this ID from `InstaMemory` Contract. setId Set token amount at this ID in `InstaMemory` Contract./ emitLogSellMulti(oneProtoData, getId, setId);
|
function _sellMulti(
OneProtoMultiData memory oneProtoData,
uint getId,
uint setId
) internal returns (OneProtoMultiData memory) {
uint _sellAmt = getUint(getId, oneProtoData._sellAmt);
oneProtoData._sellAmt = _sellAmt == uint(-1) ?
getTokenBal(oneProtoData.sellToken) :
_sellAmt;
oneProtoData._buyAmt = oneProtoSwapMulti(oneProtoData);
setUint(setId, oneProtoData._buyAmt);
return oneProtoData;
}
| 104,295
|
./partial_match/42/0x1827E00dB6C889A332D1Ce532A341fE1f752038F/sources/Exchange.sol
|
overridden by state variable can not be overridden by state variable due to type `Deciaml.decimal` File: contracts/interface/ICFD.sol
|
interface ICFD {
function getMMLiquidity(address _exchange) external view returns (SignedDecimal.signedDecimal memory);
}
| 3,301,058
|
/**
*Submitted for verification at Etherscan.io on 2021-06-16
*/
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
interface IERC20 {
function balanceOf(address) external view returns (uint256);
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint256);
}
interface IUniswapV3Pool {
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
}
interface IGUniPool {
function token0() external view returns (IERC20);
function token1() external view returns (IERC20);
function pool() external view returns (IUniswapV3Pool);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function getMintAmounts(uint256 amount0Max, uint256 amount1Max)
external
view
returns (
uint256 amount0,
uint256 amount1,
uint256 mintAmount
);
function getPositionID() external view returns (bytes32 positionID);
function lowerTick() external view returns (int24);
function upperTick() external view returns (int24);
}
interface GUniResolver {
function getPoolUnderlyingBalances(IGUniPool pool)
external
view
returns (uint256 amount0, uint256 amount1);
function getUnderlyingBalances(
IGUniPool pool,
uint256 balance
) external view returns (uint256 amount0, uint256 amount1);
function getRebalanceParams(
IGUniPool pool,
uint256 amount0In,
uint256 amount1In,
uint16 slippageBPS
) external view returns (
bool zeroForOne,
uint256 swapAmount,
uint160 swapThreshold
);
}
struct StakingRewardsInfo {
address stakingRewards;
uint rewardAmount;
}
interface StakingFactoryInterface {
function stakingRewardsInfoByStakingToken(address) external view returns(StakingRewardsInfo memory);
}
interface StakingInterface {
function totalSupply() external view returns (uint256);
function rewardRate() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function earned(address account) external view returns (uint256);
function rewardPerToken() external view returns (uint256);
}
interface IndexInterface {
function master() external view returns (address);
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "math-not-safe");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "math-not-safe");
}
uint constant WAD = 10 ** 18;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
}
contract Helpers is DSMath {
GUniResolver public constant gelatoRouter = GUniResolver(0x3B01f3534c9505fE8e7cf42794a545A0d2ede976);
StakingFactoryInterface public getStakingFactory;
function updateFactory(address _stakingFactory) public {
require(msg.sender == IndexInterface(0x2971AdFa57b20E5a416aE5a708A8655A9c74f723).master(), "not-master");
require(address(getStakingFactory) != _stakingFactory, "already-enabled");
getStakingFactory = StakingFactoryInterface(_stakingFactory);
}
struct UserData {
address pool; // address of pool contract
address staking; // address of staking contract
address token0Addr; // address of token 0
address token1Addr; // address of token 1
uint poolTokenSupply; // Total supply of Pool token
uint poolToken0Bal; // balance of total pool for token0
uint poolToken1Bal; // balance of total pool for token1
uint poolTokenSupplyStaked; // total pool token locked in staking contract
uint stakingToken0Bal; // total balance of token0 in Staking
uint stakingToken1Bal; // total balance of token1 in Staking
uint rewardRate; // INST distributing per second
uint token0Bal; // balance of token 0 of user
uint token1Bal; // balance of token 1 of user
uint earned; // INST earned from staking
uint stakedBal; // user's pool token bal in staking contract
uint poolBal; // ideal pool token in user's DSA
uint totalBal; // stakedBal + poolTknBal
uint token0Decimals; // token0 decimals
uint token1Decimals; // token1 decimals
int24 currentTick; // Current price of 1 token w.r.t to other
int24 lowerTick; // Price of 1 token w.r.t to other at lower tick
int24 upperTick; // Price of 1 token w.r.t to other at upper tick
}
}
contract Resolver is Helpers {
function getSinglePosition(address user, address pool) public view returns(UserData memory _data) {
_data.pool = pool;
StakingInterface stakingContract = StakingInterface(getStakingFactory.stakingRewardsInfoByStakingToken(pool).stakingRewards);
_data.staking = address(stakingContract);
IGUniPool poolContract = IGUniPool(pool);
_data.token0Addr = address(poolContract.token0());
_data.token1Addr = address(poolContract.token1());
if (_data.staking == address(0)) {
_data.earned = 0;
_data.stakedBal = 0;
} else {
_data.earned = stakingContract.earned(user);
_data.stakedBal = stakingContract.balanceOf(user);
}
_data.poolBal = poolContract.balanceOf(user);
_data.totalBal = add(_data.stakedBal, _data.poolBal);
(_data.token0Bal, _data.token1Bal) = gelatoRouter.getUnderlyingBalances(poolContract, _data.totalBal);
_data.poolTokenSupply = poolContract.balanceOf(user);
(_data.poolToken0Bal, _data.poolToken1Bal) = gelatoRouter.getPoolUnderlyingBalances(poolContract);
_data.poolTokenSupplyStaked = stakingContract.totalSupply();
(_data.stakingToken0Bal, _data.stakingToken1Bal) = gelatoRouter.getUnderlyingBalances(poolContract, _data.poolTokenSupplyStaked);
_data.rewardRate = stakingContract.rewardRate();
_data.token0Decimals = poolContract.token0().decimals();
_data.token1Decimals = poolContract.token1().decimals();
IUniswapV3Pool uniNft = poolContract.pool();
(, _data.currentTick, , , , , ) = uniNft.slot0();
_data.lowerTick = poolContract.lowerTick();
_data.upperTick = poolContract.upperTick();
}
function getPosition(address user, address[] memory pools) public view returns(UserData[] memory _data) {
_data = new UserData[](pools.length);
for (uint i = 0; i < pools.length; i++) {
_data[i] = getSinglePosition(user, pools[i]);
}
}
/**
* @param pool - gelato pool address.
* @param amount0In - amount of token0 user wants to deposit.
* @param amount1In - amount of token1 user wants to deposit.
* @param slippage in 18 decimal where 100% = 1e18.
* @return zeroForOne - if true swap token0 for token1 else vice versa
* @return swapAmount - Amount of tokens to swap.
* @return swapThreshold - Max slippage that the swap can take.
*/
function getSwapAndDepositParams(
address pool,
uint amount0In,
uint amount1In,
uint slippage
) public view returns (
bool zeroForOne,
uint256 swapAmount,
uint160 swapThreshold
) {
uint slippageBPS = slippage / 1e16;
(zeroForOne, swapAmount, swapThreshold) = gelatoRouter.getRebalanceParams(IGUniPool(pool), amount0In, amount1In, uint16(slippageBPS));
}
/**
* @param user - address of user.
* @param pool - address of Gelato Pool.
* @param burnPercent - in 18 decimal where 100% = 1e18.
* @param slippage in 18 decimal where 100% = 1e18.
* @return burnAmt - Amount of pool tokens to burn.
* @return amount0 - Amount of token0 user will get.
* @return amount1 - Amount of token1 user will get.
* @return amount0Min - Min amount of token0 user should get.
* @return amount1Min - Min amount of token1 user should get.
*/
function getWithdrawParams(address user, address pool, uint burnPercent, uint slippage) public view returns (uint burnAmt, uint amount0, uint amount1, uint amount0Min, uint amount1Min) {
UserData memory _data = getSinglePosition(user, pool);
burnPercent = burnPercent > 1e18 ? 1e18 : burnPercent;
burnAmt = wmul(_data.totalBal, burnPercent);
amount0 = wmul(_data.token0Bal, burnPercent);
amount1 = wmul(_data.token1Bal, burnPercent);
amount0Min = wmul(amount0, sub(1e18, slippage));
amount1Min = wmul(amount1, sub(1e18, slippage));
}
}
contract InstaGUNIV3PoolResolver is Resolver {
constructor (address _stakingFactory) public {
getStakingFactory = StakingFactoryInterface(_stakingFactory);
}
string public constant name = "G-UNI-V3-Resolver-v1.0";
}
|
pool - gelato pool address. amount0In - amount of token0 user wants to deposit. amount1In - amount of token1 user wants to deposit. slippage in 18 decimal where 100% = 1e18. return zeroForOne - if true swap token0 for token1 else vice versa return swapAmount - Amount of tokens to swap. return swapThreshold - Max slippage that the swap can take./
|
function getSwapAndDepositParams(
address pool,
uint amount0In,
uint amount1In,
uint slippage
) public view returns (
bool zeroForOne,
uint256 swapAmount,
uint160 swapThreshold
) {
uint slippageBPS = slippage / 1e16;
(zeroForOne, swapAmount, swapThreshold) = gelatoRouter.getRebalanceParams(IGUniPool(pool), amount0In, amount1In, uint16(slippageBPS));
}
| 6,572,623
|
./partial_match/42220/0x6023fF93A3b37791a94B15D6AEaD488933b01Db3/sources/C/Users/guill/github/witnet/witnet-solidity-bridge/flattened/WitnetRandomness/FlattenedWitnetRandomness.sol
|
Generates a pseudo-random number uniformly distributed within the range [0 .. _range), by using the given `_nonce` value and the randomness returned by `getRandomnessAfter(_block)`. Fails under same conditions as `getRandomnessAfter(uint256)` may do. _range Range within which the uniformly-distributed random number will be generated. _nonce Nonce value enabling multiple random numbers from the same randomness value. _block Block number from which the search will start.
|
function random(uint32 _range, uint256 _nonce, uint256 _block)
external view
virtual override
returns (uint32)
{
return random(
_range,
_nonce,
keccak256(
abi.encode(
msg.sender,
getRandomnessAfter(_block)
)
)
);
}
| 3,500,484
|
./full_match/1/0x44cD00771f57488A1988136cC38EB03554db1f77/sources/browser/Wasabi.sol
|
External function call This function adjust how many token will be produced by each block, eg: changeAmountPerBlock(100) will set the produce rate to 100/block.
|
function changeInterestsPerBlock(uint value) external override requireGovernor returns (bool) {
uint old = wasabiPerBlock;
require(value != old, 'AMOUNT_PER_BLOCK_NO_CHANGE');
wasabiPerBlock = value;
emit InterestsPerBlockChanged(old, value);
return true;
}
| 3,085,217
|
./full_match/80001/0x71cDC196C4b2484D9a8743Fc8be0af9D97858775/sources/project_/contracts/ERC4907.sol
|
Get the user expires of an NFT The zero value indicates that there is no user tokenId The NFT to get the user expires for return The user expires for this NFT
|
function userExpires(
uint256 tokenId
) public view virtual returns (address, uint256, uint256) {
return (
_users[tokenId].user,
_users[tokenId].startDate,
_users[tokenId].endDate
);
}
| 5,574,073
|
pragma solidity ^0.4.2;
// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
}
contract Elements is ERC721 {
/*** EVENTS ***/
// @dev The Birth event is fired whenever a new element comes into existence.
event Birth(uint256 tokenId, string name, address owner);
// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
// @dev Transfer event as defined in current draft of ERC721. Ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS, VARIABLES ***/
// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoElements"; // solhint-disable-line
string public constant SYMBOL = "CREL"; // solhint-disable-line
uint256 private periodicStartingPrice = 5 ether;
uint256 private elementStartingPrice = 0.005 ether;
uint256 private scientistStartingPrice = 0.1 ether;
uint256 private specialStartingPrice = 0.05 ether;
uint256 private firstStepLimit = 0.05 ether;
uint256 private secondStepLimit = 0.75 ether;
uint256 private thirdStepLimit = 3 ether;
bool private periodicTableExists = false;
uint256 private elementCTR = 0;
uint256 private scientistCTR = 0;
uint256 private specialCTR = 0;
uint256 private constant elementSTART = 1;
uint256 private constant scientistSTART = 1000;
uint256 private constant specialSTART = 10000;
uint256 private constant specialLIMIT = 5000;
/*** STORAGE ***/
// @dev A mapping from element IDs to the address that owns them. All elements have
// some valid owner address.
mapping (uint256 => address) public elementIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) private ownershipTokenCount;
// @dev A mapping from ElementIDs to an address that has been approved to call
// transferFrom(). Each Element can only have one approved address for transfer
// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public elementIndexToApproved;
// @dev A mapping from ElementIDs to the price of the token.
mapping (uint256 => uint256) private elementIndexToPrice;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cooAddress;
/*** DATATYPES ***/
struct Element {
uint256 tokenId;
string name;
uint256 scientistId;
}
mapping(uint256 => Element) elements;
uint256[] tokens;
/*** ACCESS MODIFIERS ***/
// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
// Access modifier for contract owner only functionality
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
_;
}
/*** CONSTRUCTOR ***/
function Elements() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
createContractPeriodicTable("Periodic");
}
/*** PUBLIC FUNCTIONS ***/
// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
// @param _to The address to be granted transfer approval. Pass address(0) to
// clear all approvals.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _tokenId) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
elementIndexToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
// For querying balance of a particular account
// @param _owner The address for balance query
// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
// @notice Returns all the relevant information about a specific element.
// @param _tokenId The tokenId of the element of interest.
function getElement(uint256 _tokenId) public view returns (
uint256 tokenId,
string elementName,
uint256 sellingPrice,
address owner,
uint256 scientistId
) {
Element storage element = elements[_tokenId];
tokenId = element.tokenId;
elementName = element.name;
sellingPrice = elementIndexToPrice[_tokenId];
owner = elementIndexToOwner[_tokenId];
scientistId = element.scientistId;
}
function implementsERC721() public pure returns (bool) {
return true;
}
// For querying owner of token
// @param _tokenId The tokenID for owner inquiry
// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId) public view returns (address owner) {
owner = elementIndexToOwner[_tokenId];
require(owner != address(0));
}
function payout(address _to) public onlyCLevel {
_payout(_to);
}
// Allows someone to send ether and obtain the token
function purchase(uint256 _tokenId) public payable {
address oldOwner = elementIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = elementIndexToPrice[_tokenId];
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
require(sellingPrice > 0);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
uint256 ownerPayout = SafeMath.mul(SafeMath.div(sellingPrice, 100), 96);
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
uint256 feeOnce = SafeMath.div(SafeMath.sub(sellingPrice, ownerPayout), 4);
uint256 fee_for_dev = SafeMath.mul(feeOnce, 2);
// Pay previous tokenOwner if owner is not contract
// and if previous price is not 0
if (oldOwner != address(this)) {
// old owner gets entire initial payment back
oldOwner.transfer(ownerPayout);
} else {
fee_for_dev = SafeMath.add(fee_for_dev, ownerPayout);
}
// Taxes for Periodic Table owner
if (elementIndexToOwner[0] != address(this)) {
elementIndexToOwner[0].transfer(feeOnce);
} else {
fee_for_dev = SafeMath.add(fee_for_dev, feeOnce);
}
// Taxes for Scientist Owner for given Element
uint256 scientistId = elements[_tokenId].scientistId;
if ( scientistId != scientistSTART ) {
if (elementIndexToOwner[scientistId] != address(this)) {
elementIndexToOwner[scientistId].transfer(feeOnce);
} else {
fee_for_dev = SafeMath.add(fee_for_dev, feeOnce);
}
} else {
fee_for_dev = SafeMath.add(fee_for_dev, feeOnce);
}
if (purchaseExcess > 0) {
msg.sender.transfer(purchaseExcess);
}
ceoAddress.transfer(fee_for_dev);
_transfer(oldOwner, newOwner, _tokenId);
//TokenSold(_tokenId, sellingPrice, elementIndexToPrice[_tokenId], oldOwner, newOwner, elements[_tokenId].name);
// Update prices
if (sellingPrice < firstStepLimit) {
// first stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 100);
} else if (sellingPrice < secondStepLimit) {
// second stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 150), 100);
} else if (sellingPrice < thirdStepLimit) {
// third stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 130), 100);
} else {
// fourth stage
elementIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 100);
}
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return elementIndexToPrice[_tokenId];
}
// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
// @dev Assigns a new address to act as the COO. Only available to the current COO.
// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
// @notice Allow pre-approved user to take ownership of a token
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = elementIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
// @param _owner The owner whose element tokens we are interested in.
// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
// expensive (it walks the entire Elements array looking for elements belonging to owner),
// but it also returns a dynamic array, which is only supported for web3 calls, and
// not contract-to-contract calls.
function tokensOfOwner(address _owner) public 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 totalElements = totalSupply();
uint256 resultIndex = 0;
uint256 elementId;
for (elementId = 0; elementId < totalElements; elementId++) {
uint256 tokenId = tokens[elementId];
if (elementIndexToOwner[tokenId] == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
// For querying totalSupply of token
// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total) {
return tokens.length;
}
// Owner initates the transfer of the token to another account
// @param _to The address for the token to be transferred to.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function transfer( address _to, uint256 _tokenId ) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
// Third-party initiates transfer of token from address _from to address _to
// @param _from The address for the token to be transferred from.
// @param _to The address for the token to be transferred to.
// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function transferFrom( address _from, address _to, uint256 _tokenId) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
/*** PRIVATE FUNCTIONS ***/
// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
// For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return elementIndexToApproved[_tokenId] == _to;
}
// Private method for creating Element
function _createElement(uint256 _id, string _name, address _owner, uint256 _price, uint256 _scientistId) private returns (string) {
uint256 newElementId = _id;
// 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(newElementId == uint256(uint32(newElementId)));
elements[_id] = Element(_id, _name, _scientistId);
Birth(newElementId, _name, _owner);
elementIndexToPrice[newElementId] = _price;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newElementId);
tokens.push(_id);
return _name;
}
// @dev Creates Periodic Table as first element
function createContractPeriodicTable(string _name) public onlyCEO {
require(periodicTableExists == false);
_createElement(0, _name, address(this), periodicStartingPrice, scientistSTART);
periodicTableExists = true;
}
// @dev Creates a new Element with the given name and Id
function createContractElement(string _name, uint256 _scientistId) public onlyCEO {
require(periodicTableExists == true);
uint256 _id = SafeMath.add(elementCTR, elementSTART);
uint256 _scientistIdProcessed = SafeMath.add(_scientistId, scientistSTART);
_createElement(_id, _name, address(this), elementStartingPrice, _scientistIdProcessed);
elementCTR = SafeMath.add(elementCTR, 1);
}
// @dev Creates a new Scientist with the given name Id
function createContractScientist(string _name) public onlyCEO {
require(periodicTableExists == true);
// to start from 1001
scientistCTR = SafeMath.add(scientistCTR, 1);
uint256 _id = SafeMath.add(scientistCTR, scientistSTART);
_createElement(_id, _name, address(this), scientistStartingPrice, scientistSTART);
}
// @dev Creates a new Special Card with the given name Id
function createContractSpecial(string _name) public onlyCEO {
require(periodicTableExists == true);
require(specialCTR <= specialLIMIT);
// to start from 10001
specialCTR = SafeMath.add(specialCTR, 1);
uint256 _id = SafeMath.add(specialCTR, specialSTART);
_createElement(_id, _name, address(this), specialStartingPrice, scientistSTART);
}
// Check for token ownership
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == elementIndexToOwner[_tokenId];
}
//**** HELPERS for checking elements, scientists and special cards
function checkPeriodic() public view returns (bool) {
return periodicTableExists;
}
function getTotalElements() public view returns (uint256) {
return elementCTR;
}
function getTotalScientists() public view returns (uint256) {
return scientistCTR;
}
function getTotalSpecials() public view returns (uint256) {
return specialCTR;
}
//**** HELPERS for changing prices limits and steps if it would be bad, community would like different
function changeStartingPricesLimits(uint256 _elementStartPrice, uint256 _scientistStartPrice, uint256 _specialStartPrice) public onlyCEO {
elementStartingPrice = _elementStartPrice;
scientistStartingPrice = _scientistStartPrice;
specialStartingPrice = _specialStartPrice;
}
function changeStepPricesLimits(uint256 _first, uint256 _second, uint256 _third) public onlyCEO {
firstStepLimit = _first;
secondStepLimit = _second;
thirdStepLimit = _third;
}
// in case of error when assigning scientist to given element
function changeScientistForElement(uint256 _tokenId, uint256 _scientistId) public onlyCEO {
Element storage element = elements[_tokenId];
element.scientistId = SafeMath.add(_scientistId, scientistSTART);
}
function changeElementName(uint256 _tokenId, string _name) public onlyCEO {
Element storage element = elements[_tokenId];
element.name = _name;
}
// This function can be used by the owner of a token to modify the current price
function modifyTokenPrice(uint256 _tokenId, uint256 _newPrice) public payable {
require(_newPrice > elementStartingPrice);
require(elementIndexToOwner[_tokenId] == msg.sender);
require(_newPrice < elementIndexToPrice[_tokenId]);
if ( _tokenId == 0) {
require(_newPrice > periodicStartingPrice);
} else if ( _tokenId < 1000) {
require(_newPrice > elementStartingPrice);
} else if ( _tokenId < 10000 ) {
require(_newPrice > scientistStartingPrice);
} else {
require(_newPrice > specialStartingPrice);
}
elementIndexToPrice[_tokenId] = _newPrice;
}
// For paying out balance on contract
function _payout(address _to) private {
if (_to == address(0)) {
ceoAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
// @dev Assigns ownership of a specific Element to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
// Since the number of elements is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
elementIndexToOwner[_tokenId] = _to;
// When creating new elements _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete elementIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
}
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;
}
}
|
For querying balance of a particular account _owner The address for balance query Required for ERC-721 compliance.
|
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
| 5,503,514
|
pragma solidity ^0.4.23;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract GetAchieveICO is Ownable {
using SafeMath for uint;
address public beneficiary;
uint256 public decimals;
uint256 public softCap; // in Wei
uint256 public hardCap; // in Wei
uint256 public amountRaised; // in Wei
uint256 public amountSold; // Amount of sold tokens with decimals
uint256 public maxAmountToSell; // Amount of tokens to sell for current Round [Pre Sale - 192M GAT, Sale - 228M GAT]
uint256 deadline1; // Pre Sale deadline
uint256 deadline2; // Sale deadline
uint256 oneWeek; // 1 week timeline
uint256 public price; // Current price
uint256 price0; // Sale period price (ICO)
uint256 price1; // Pre Sale period price Round 1
uint256 price2; // Pre Sale period price Round 2
uint256 price3; // Pre Sale period price Round 3
uint256 price4; // Pre Sale period price Round 4
uint256 price5; // Pre Sale period price Round 5
uint256 price6; // Pre Sale period price Round 6
uint256 price7; // Pre Sale period price Round 7
ERC20 public token;
mapping(address => uint256) balances;
bool public fundingGoalReached = false;
bool public crowdsaleClosed = true; // Closed till manually start by the owner
event GoalReached(address recipient, uint256 totalAmountRaised);
event FundTransfer(address backer, uint256 amount, bool isContribution);
/**
* Constructor function
*
* Initialization
*/
constructor(
address wallet,
ERC20 addressOfToken
) public {
beneficiary = wallet;
decimals = 18;
softCap = 4000 * 1 ether;
hardCap = 12000 * 1 ether;
maxAmountToSell = 192000000 * 10 ** decimals; // Pre Sale 192M GAT. Then 228M GAT will be added in time of Sale period
// Price rates
price0 = 40; // 0.000040 ETH (in Wei)
price1 = 20; // 0.000020 ETH (in Wei)
price2 = 24; // 0.000024 ETH (in Wei)
price3 = 24; // 0.000024 ETH (in Wei)
price4 = 28; // 0.000028 ETH (in Wei)
price5 = 28; // 0.000028 ETH (in Wei)
price6 = 32; // 0.000032 ETH (in Wei)
price7 = 32; // 0.000032 ETH (in Wei)
price = price1; // Set Pre Sale Round 1 token price as current
oneWeek = 7 * 1 days;
deadline2 = now + 50 * oneWeek; // Just for blocking checkGoalReached() function call till Crowdsale start
token = addressOfToken;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint) {
return balances[_owner];
}
/**
* Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
function () payable public {
require(!crowdsaleClosed);
require(_validateSaleDate());
require(msg.sender != address(0));
uint256 amount = msg.value;
require(amount != 0);
require(amount >= 10000000000000000); // min 0.01 ETH
require(amount <= hardCap); // Hard cap
uint256 tokens = amount.mul(10 ** 6); // Add 6 zeros in the end of 'amount' to use correct price rate
tokens = tokens.div(price); // Amount of tokens to sell for the current price rate
require(amountSold.add(tokens) <= maxAmountToSell); // Check token oversell for the current Round
balances[msg.sender] = balances[msg.sender].add(amount);
amountRaised = amountRaised.add(amount);
amountSold = amountSold.add(tokens); // Update amount of sold tokens
token.transfer(msg.sender, tokens);
emit FundTransfer(msg.sender, amount, true);
}
/**
* @dev Validation of Pre Sale period
* @return bool
*/
function _validateSaleDate() internal returns (bool) {
// Pre Sale
if(now <= deadline1) {
uint256 dateDif = deadline1.sub(now);
if (dateDif <= 2 * 1 days) {
price = price7; // Round 7
return true;
} else if (dateDif <= 4 * 1 days) {
price = price6; // Round 6
return true;
} else if (dateDif <= 6 * 1 days) {
price = price5; // Round 5
return true;
} else if (dateDif <= 8 * 1 days) {
price = price4; // Round 4
return true;
} else if (dateDif <= 10 * 1 days) {
price = price3; // Round 3
return true;
} else if (dateDif <= 12 * 1 days) {
price = price2; // Round 2
return true;
} else if (dateDif <= 14 * 1 days) {
price = price1; // Round 1
return true;
} else {
price = 25; // Default average value
return true;
}
}
// Sale
if (now >= (deadline1.add(oneWeek)) && now <= deadline2) {
maxAmountToSell = 420000000 * 10 ** decimals; // Pre Sale + Sale = 192M GAT + 228M GAT
price = price0; // Sale token price
return true;
}
// After Sale
if (now >= deadline2) {
crowdsaleClosed = true; // Crowdsale period is finished
return false;
}
return false;
}
/**
* @dev Start Sale
*/
function startCrowdsale() onlyOwner public returns (bool) {
deadline1 = now + 2 * oneWeek; // Set Pre Sale deadline 2 weeks
deadline2 = deadline1 + oneWeek + 8 * oneWeek; // Set Sale deadline 8 weeks
crowdsaleClosed = false; // Start Crowdsale period
return true;
}
modifier afterDeadline() { if (now >= deadline2) _; }
/**
* Check if goal was reached
* Checks if the goal or time limit has been reached and ends the campaign
*/
function checkGoalReached() onlyOwner afterDeadline public {
if (amountRaised >= softCap) {
fundingGoalReached = true;
emit GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true; // Close Crowdsale
}
/**
* Withdraw the funds
*
* Checks to see if goal or time limit has been reached, and if so, and the funding goal was reached,
* sends the entire amount to the beneficiary. If goal was not reached, each contributor can withdraw
* the amount they contributed.
*/
function safeWithdrawal() afterDeadline public {
require(!fundingGoalReached);
require(crowdsaleClosed);
uint256 amount = balances[msg.sender];
balances[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
emit FundTransfer(msg.sender, amount, false);
} else {
balances[msg.sender] = amount;
}
}
}
/**
* Withdraw the funds
*/
function safeWithdrawFunds(uint256 amount) onlyOwner public returns (bool) {
require(beneficiary == msg.sender);
if (beneficiary.send(amount)) {
return true;
} else {
return false;
}
}
/**
* Withdraw rest of tokens from smart contract balance to the owner's wallet
* if funding goal is not reached and Crowdsale is already closed.
*
* Can be used for Airdrop if funding goal is not reached.
*/
function safeWithdrawTokens(uint256 amount) onlyOwner afterDeadline public returns (bool) {
require(!fundingGoalReached);
require(crowdsaleClosed);
token.transfer(beneficiary, amount);
emit FundTransfer(beneficiary, amount, false);
}
}
|
Withdraw the funds/
|
function safeWithdrawFunds(uint256 amount) onlyOwner public returns (bool) {
require(beneficiary == msg.sender);
if (beneficiary.send(amount)) {
return true;
return false;
}
}
| 15,840,426
|
./full_match/5/0xFf3820bd8196C6Fdb5568d7CB1814ecC305787a5/sources/src/AmphorSyntheticVault.sol
|
The `previewWithdraw` function is used to calculate the shares amount received in exchange of the specified underlying amount. assets The underlying assets amount to be converted into shares. return Amount of shares received in exchange of the specified underlying assets amount./
|
function previewWithdraw(uint256 assets) public view returns (uint256) {
return _convertToShares(assets, Math.Rounding.Up);
}
| 1,860,062
|
//Address: 0x398e41ac3d5972b4bac2320cd130c7a25ca446f7
//Contract name: Crowdsale
//Balance: 0 Ether
//Verification Date: 4/6/2018
//Transacion Count: 1670
// CODE STARTS HERE
pragma solidity ^0.4.21;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title 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;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales.
*
* Presales:
* Certain addresses are allowed to buy at a presale rate during the presale period. The
* contribution of the investor needs to be of at least 5 ETH. A maximum of 15 million tokens
* in total can be bought at the presale rate. Once the presale has been instructed to end, it
* is not possible to enable it again.
*
* Sales:
* Any address can purchase at the regular sale price. Sales can be pauses, resumed, and stopped.
*
* Minting:
* The transferTokens function will mint the tokens in the Token contract. After the minting
* is done, the Crowdsale is reset.
*
* Refunds:
* A investor can be refunded by the owner. Calling the refund function resets the tokens bought
* to zero for that investor. The Ether refund needs to be processed manually. It is important
* to record how many tokens the investor had bought before calling refund().
*
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
StandardToken public token;
// How many token units a buyer gets per wei
uint256 public rate;
// How many token units a buyer gets per wei if entitled to the presale
uint public presaleRate;
// Amount of wei raised
uint256 public weiRaised;
// Administrator of the sale
address public owner;
// How many tokens each address bought at the normal rate
mapping (address => uint) public regularTokensSold;
// How many tokens each address bought at the presale rate
mapping (address => uint) public presaleTokensSold;
// List of all the investors
address[] public investors;
// Whether the sale is active
bool public inSale = true;
// Whether the presale is active
bool public inPresale = true;
// How many tokens each address can buy at the presale rate
mapping (address => uint) public presaleAllocations;
// The total number of tokens bought
uint256 public totalPresaleTokensSold = 0;
// The total number of tokens bought
uint256 public totalRegularTokensSold = 0;
// The maximum number of tokens which can be sold during presale
uint256 constant public PRESALETOKENMAXSALES = 15000000000000000000000000;
// The maximum number of tokens which can be sold during regular sale
uint256 public regularTokenMaxSales = 16000000000000000000000000;
// The minimum investment (5 ETH) during presale
uint256 constant public MINIMUMINVESTMENTPRESALE = 5000000000000000000;
// The minimum investment (5 ETH) during sale
uint256 constant public MINIMUMINVESTMENTSALE = 1000000000000000000;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyDuringPresale() {
require(inPresale);
_;
}
modifier onlyWhenSalesEnabled() {
require(inSale);
_;
}
/**
* 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
* @param rate the rate at which the tokens were purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 rate);
/**
* Constructor for the crowdsale
* @param _owner owner of the contract, which can call privileged functions, and where every ether
* is sent to
* @param _rate the rate for regular sales
* @param _rate the rate for presales
* @param _ownerInitialTokens the number of tokens the owner is allocated initially
*/
function Crowdsale(
address _owner,
uint256 _rate,
uint256 _presaleRate,
uint256 _ownerInitialTokens
) public payable {
require(_rate > 0);
require(_presaleRate > 0);
require(_owner != address(0));
rate = _rate;
presaleRate = _presaleRate;
owner = _owner;
investors.push(owner);
regularTokensSold[owner] = _ownerInitialTokens;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
function () external payable {
buyTokens();
}
/**
* Sets the address of the Token contract.
*/
function setToken(StandardToken _token) public onlyOwner {
token = _token;
}
/**
* Buy a token at presale price. Converts ETH to as much QNT the sender can purchase. Any change
* is refunded to the sender. Minimum contribution is 5 ETH.
*/
function buyPresaleTokens() onlyDuringPresale onlyWhenSalesEnabled public payable {
address _beneficiary = msg.sender;
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary);
require(weiAmount >= MINIMUMINVESTMENTPRESALE);
uint256 presaleAllocation = presaleAllocations[_beneficiary];
uint256 presaleTokens = _min256(weiAmount.mul(presaleRate), presaleAllocation);
_recordPresalePurchase(_beneficiary, presaleTokens);
// Remove presale tokens allocation
presaleAllocations[_beneficiary] = presaleAllocations[_beneficiary].sub(presaleTokens);
uint256 weiCharged = presaleTokens.div(presaleRate);
// Return any extra Wei to the sender
uint256 change = weiAmount.sub(weiCharged);
_beneficiary.transfer(change);
// Update total number of Wei raised
weiRaised = weiRaised.add(weiAmount.sub(change));
emit TokenPurchase(msg.sender, _beneficiary, weiCharged, presaleTokens, presaleRate);
// Forward the funds to owner
_forwardFunds(weiCharged);
}
/**
* Buy a token at sale price. Minimum contribution is 1 ETH.
*/
function buyTokens() onlyWhenSalesEnabled public payable {
address _beneficiary = msg.sender;
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary);
require(weiAmount >= MINIMUMINVESTMENTSALE);
uint256 tokens = weiAmount.mul(rate);
// Check we haven't sold too many tokens
totalRegularTokensSold = totalRegularTokensSold.add(tokens);
require(totalRegularTokensSold <= regularTokenMaxSales);
// Update total number of Wei raised
weiRaised = weiRaised.add(weiAmount);
investors.push(_beneficiary);
// Give tokens
regularTokensSold[_beneficiary] = regularTokensSold[_beneficiary].add(tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens, rate);
// Forward the funds to owner
_forwardFunds(weiAmount);
}
/**
* Records a purchase which has been completed before the instantiation of this contract.
* @param _beneficiary the investor
* @param _presaleTokens the number of tokens which the investor has bought
*/
function recordPresalePurchase(address _beneficiary, uint256 _presaleTokens) public onlyOwner {
weiRaised = weiRaised.add(_presaleTokens.div(presaleRate));
return _recordPresalePurchase(_beneficiary, _presaleTokens);
}
function enableSale() onlyOwner public {
inSale = true;
}
function disableSale() onlyOwner public {
inSale = false;
}
function endPresale() onlyOwner public {
inPresale = false;
// Convert the unsold presale tokens to regular tokens
uint256 remainingPresaleTokens = PRESALETOKENMAXSALES.sub(totalPresaleTokensSold);
regularTokenMaxSales = regularTokenMaxSales.add(remainingPresaleTokens);
}
/**
* Mints the tokens in the Token contract.
*/
function transferTokens() public onlyOwner {
for (uint256 i = 0; i < investors.length; i = i.add(1)) {
address investor = investors[i];
uint256 tokens = regularTokensSold[investor];
uint256 presaleTokens = presaleTokensSold[investor];
regularTokensSold[investor] = 0;
presaleTokensSold[investor] = 0;
if (tokens > 0) {
_deliverTokens(token, investor, tokens);
}
if (presaleTokens > 0) {
_deliverTokens(token, investor, presaleTokens);
}
}
}
/**
* Mints the tokens in the Token contract. With Offset and Limit
*/
function transferTokensWithOffsetAndLimit(uint256 offset, uint256 limit) public onlyOwner {
for (uint256 i = offset; i < _min256(investors.length,offset+limit); i = i.add(1)) {
address investor = investors[i];
uint256 tokens = regularTokensSold[investor];
uint256 presaleTokens = presaleTokensSold[investor];
regularTokensSold[investor] = 0;
presaleTokensSold[investor] = 0;
if (tokens > 0) {
_deliverTokens(token, investor, tokens);
}
if (presaleTokens > 0) {
_deliverTokens(token, investor, presaleTokens);
}
}
}
/**
* Clears the number of tokens bought by an investor. The ETH refund needs to be processed
* manually.
*/
function refund(address investor) onlyOwner public {
require(investor != owner);
uint256 regularTokens = regularTokensSold[investor];
totalRegularTokensSold = totalRegularTokensSold.sub(regularTokens);
weiRaised = weiRaised.sub(regularTokens.div(rate));
uint256 presaleTokens = presaleTokensSold[investor];
totalPresaleTokensSold = totalPresaleTokensSold.sub(presaleTokens);
weiRaised = weiRaised.sub(presaleTokens.div(presaleRate));
regularTokensSold[investor] = 0;
presaleTokensSold[investor] = 0;
// Manually send ether to the account
}
/**
* Accessor for Index
*/
function getInvestorAtIndex(uint256 _index) public view returns(address) {
return investors[_index];
}
/**
* Return the length of the investors array
*/
function getInvestorsLength() public view returns(uint256) {
return investors.length;
}
/**
* Get the number of tokens bought at the regular price for an address.
*/
function getNumRegularTokensBought(address _address) public view returns(uint256) {
return regularTokensSold[_address];
}
/**
* Get the number of tokens bought at the presale price for an address.
*/
function getNumPresaleTokensBought(address _address) public view returns(uint256) {
return presaleTokensSold[_address];
}
/**
* Get the number of tokens which an investor can purchase at presale rate.
*/
function getPresaleAllocation(address investor) view public returns(uint256) {
return presaleAllocations[investor];
}
/**
* Set the number of tokens which an investor can purchase at presale rate.
*/
function setPresaleAllocation(address investor, uint allocation) onlyOwner public {
presaleAllocations[investor] = allocation;
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
*/
function _preValidatePurchase(address _beneficiary) internal pure {
require(_beneficiary != address(0));
}
/**
* @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(StandardToken _token, address _beneficiary, uint256 _tokenAmount) internal {
_token.mint(_beneficiary, _tokenAmount);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds(uint256 amount) internal {
owner.transfer(amount);
}
function _min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* Records a presale purchase.
* @param _beneficiary the investor
* @param _presaleTokens the number of tokens which the investor has bought
*/
function _recordPresalePurchase(address _beneficiary, uint256 _presaleTokens) internal {
// Check we haven't sold too many presale tokens
totalPresaleTokensSold = totalPresaleTokensSold.add(_presaleTokens);
require(totalPresaleTokensSold <= PRESALETOKENMAXSALES);
investors.push(_beneficiary);
// Give presale tokens
presaleTokensSold[_beneficiary] = presaleTokensSold[_beneficiary].add(_presaleTokens);
}
}
/**
* @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_ = 45467000000000000000000000;
/**
* @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);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
// Name of the token
string constant public name = "Quant";
// Token abbreviation
string constant public symbol = "QNT";
// Decimal places
uint8 constant public decimals = 18;
// Zeros after the point
uint256 constant public DECIMAL_ZEROS = 1000000000000000000;
mapping (address => mapping (address => uint256)) internal allowed;
address public crowdsale;
modifier onlyCrowdsale() {
require(msg.sender == crowdsale);
_;
}
function StandardToken(address _crowdsale) public {
require(_crowdsale != address(0));
crowdsale = _crowdsale;
}
function mint(address _address, uint256 _value) public onlyCrowdsale {
balances[_address] = balances[_address].add(_value);
emit Transfer(0, _address, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
|
Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. _beneficiary Address performing the token purchase/
|
function _preValidatePurchase(address _beneficiary) internal pure {
require(_beneficiary != address(0));
}
| 5,438,380
|
./full_match/42220/0x6e512BFC33be36F2666754E996ff103AD1680Cc9/sources/project_/contracts/WrappedToken.sol
|
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) external onlyMintBurnAuthority {
require(account != address(0), "ERC20: burn from the zero address");
require(_balances[account] >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = _balances[account] - amount;
_totalSupply = _totalSupply - amount;
emit Transfer(account, address(0), amount);
}
| 16,342,683
|
./full_match/1/0x03f2a869915984b9BEd52C53eE492668a326BC18/sources/src/diamonds/shared/libs/LibDiamond.sol
|
add facet for selector "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8" clear selector position in slot and add selector if slot is full then write it to storage "_selectorSlot >> 3" is a gas efficient division by 8 "_selectorSlot / 8" only useful if immutable functions exist replace old facet address get last selectorSlot adding a block here prevents stack too deep error only useful if immutable functions exist replace selector with last selector in ds.facets gets the last selector update last selector slot position info clears the selector we are deleting and puts the last selector in its place. update storage with the modified slot clears the selector we are deleting and puts the last selector in its place.
|
function addReplaceRemoveFacetSelectors(
uint256 _selectorCount,
bytes32 _selectorSlot,
address _newFacetAddress,
IDiamondCut.FacetCutAction _action,
bytes4[] memory _selectors
) internal returns (uint256, bytes32) {
DiamondStorage storage ds = diamondStorage();
require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
if (_action == IDiamondCut.FacetCutAction.Add) {
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
require(address(bytes20(oldFacet)) == address(0), "LibDiamondCut: Can't add function that already exists");
ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount);
uint256 selectorInSlotPosition = (_selectorCount & 7) << 5;
_selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) | (bytes32(selector) >> selectorInSlotPosition);
if (selectorInSlotPosition == 224) {
ds.selectorSlots[_selectorCount >> 3] = _selectorSlot;
_selectorSlot = 0;
}
_selectorCount++;
}
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
address oldFacetAddress = address(bytes20(oldFacet));
require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function");
require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function");
require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist");
ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress);
}
require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
if (_selectorSlot == 0) {
selectorSlotCount--;
_selectorSlot = ds.selectorSlots[selectorSlotCount];
selectorInSlotIndex = 7;
selectorInSlotIndex--;
}
bytes4 lastSelector;
uint256 oldSelectorsSlotCount;
uint256 oldSelectorInSlotPosition;
{
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
require(address(bytes20(oldFacet)) != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
require(address(bytes20(oldFacet)) != address(this), "LibDiamondCut: Can't remove immutable function");
lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex << 5));
if (lastSelector != selector) {
ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]);
}
delete ds.facets[selector];
uint256 oldSelectorCount = uint16(uint256(oldFacet));
}
if (oldSelectorsSlotCount != selectorSlotCount) {
bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount];
oldSelectorSlot = (oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition);
ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot;
_selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition);
}
if (selectorInSlotIndex == 0) {
delete ds.selectorSlots[selectorSlotCount];
_selectorSlot = 0;
}
}
_selectorCount = selectorSlotCount * 8 + selectorInSlotIndex;
revert("LibDiamondCut: Incorrect FacetCutAction");
}
return (_selectorCount, _selectorSlot);
}
| 8,366,598
|
pragma solidity ^0.4.4;
import "Marketplace.sol";
contract StandardMarketplace is Marketplace {
/* Fields */
address private owner;
Token public token;
/* Mappings */
mapping(address => Offer) public offers; //Tradeable => Offer
mapping(address => mapping(address => uint)) private balance; //Tradeable => Buyer => Balance
/* Modifiers */
modifier isBuyerOf(Tradeable _item) { if(offers[_item].buyer == msg.sender) _; else throw; }
modifier isOwnerOf(Tradeable _item) { if(msg.sender == _item.owner()) _; else throw; }
modifier isAuthorizedToSell(Tradeable _item) { if(_item.isAuthorizedToSell(this)) _; else throw; }
function StandardMarketplace(Token _token) {
token = _token;
if(token.totalSupply() <= 0) throw; //This seams to be an invalid contract
if(token.balanceOf(this) != 0) throw;
}
function extendOffer(Tradeable _item, address _buyer, uint _price)
isOwnerOf(_item)
isAuthorizedToSell(_item)
returns (bool success) {
if(offers[_item].state != OfferStates.Initial) return false;
if(_price < 0) return false;
addOffer(_item, Offer({
seller: msg.sender,
buyer: _buyer,
amount:_price,
state: OfferStates.Extended
}));
SellerAddedOffer(_item);
return true;
}
function acceptOffer(Tradeable _item) isBuyerOf(_item) returns (bool success) {
var offer = offers[_item];
/* Offer can only be accepted once */
if(offer.state != OfferStates.Extended) return false;
if(offer.amount > 0){
/* Check if the buyer have sufficient funds */
if(token.allowance(offer.buyer, this) < offer.amount) return false;
/* Transfer funds from the buyer to the market */
if(!token.transferFrom(offer.buyer, this, offer.amount)) throw;
balance[_item][offer.buyer] = offer.amount;
}
/* Accept the offer */
offer.state = OfferStates.Accepted;
BuyerAcceptedOffer(_item);
return true;
}
function revokeOffer(Tradeable _item) isOwnerOf(_item) returns (bool success) {
var offer = offers[_item];
/* If the offer is not added then the state is initial */
if(offers[_item].state == OfferStates.Initial) return false;
var amount = balance[_item][offer.buyer];
if(offer.state == OfferStates.Accepted && amount > 0) {
/* transferring all locked funds back to the buyer */
balance[_item][offer.buyer] = 0;
if(!token.transfer(offer.buyer, amount)) throw;
}
/* Revoke offer */
SellerRevokedOffer(_item);
removeOffer(_item, offers[_item]);
return true;
}
function completeTransaction(Tradeable _item) isBuyerOf(_item)
returns (bool success) {
/* Getting the offer */
var offer = offers[_item];
/* Can only complete the transaction if the offer was accepted */
if(offer.state != OfferStates.Accepted) return false;
if(offer.amount > 0){
/* The buyer must have sufficient funds */
if(balance[_item][offer.buyer] < offer.amount) return false;
/* Transferring funds to the seller */
balance[_item][offer.buyer] -= offer.amount;
if(!token.transfer(offer.seller, offer.amount)) throw;
}
/* Transferring ownership to the buyer */
_item.transferOwnership(offer.buyer);
BuyerCompletedTransaction(_item);
removeOffer(_item, offers[_item]);
return true;
}
function abortTransaction(Tradeable _item) isBuyerOf(_item)
returns (bool success) {
/* Getting the offer */
var offer = offers[_item];
/* Can only abort the transaction if the offer was accepted */
if(offer.state != OfferStates.Accepted) return false;
/* Transferring all locked funds back to the buyer */
var amount = balance[_item][offer.buyer];
if(amount > 0){
balance[_item][offer.buyer] = 0;
if(!token.transfer(offer.buyer, amount)) throw;
}
/* Cancel sale of the item */
BuyerAbortedTransaction(_item);
removeOffer(_item, offers[_item]);
return true;
}
function addOffer(Tradeable _item, Offer _offer) private {
offers[_item] = _offer;
onOfferAdded(_item,_offer);
}
function removeOffer(Tradeable _item, Offer _offer) private {
delete offers[_item];
onOfferRemoved(_item,_offer);
}
function onOfferAdded(Tradeable _item, Offer _offer) internal {}
function onOfferRemoved(Tradeable _item, Offer _offer) internal {}
enum OfferStates { Initial, Extended, Accepted }
struct Offer {
address seller;
address buyer;
uint amount; //The purchase cost
OfferStates state; //Whether or not the offer is accepted
}
/* Ether can't be transferred to this account */
function () { throw; }
}
|
If the offer is not added then the state is initial /
|
function revokeOffer(Tradeable _item) isOwnerOf(_item) returns (bool success) {
var offer = offers[_item];
if(offers[_item].state == OfferStates.Initial) return false;
var amount = balance[_item][offer.buyer];
if(offer.state == OfferStates.Accepted && amount > 0) {
balance[_item][offer.buyer] = 0;
if(!token.transfer(offer.buyer, amount)) throw;
removeOffer(_item, offers[_item]);
return true;
}
| 12,965,202
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./FEEVMembershipNFT.sol";
import "hardhat/console.sol";
/// @dev Smart contract to handle sale of several NFT collections
contract SalesContract is AccessControl {
/// @dev It is emitted when new purchase will be made
/// @param user Account of buyer
/// @param nftCollection Address of collection's NFT contract
/// @param price Amount of payment token
/// @param boughtNFTs Amount of bought NFT tokens
event Purchase(
address indexed user,
address indexed nftCollection,
uint256 price,
uint256 boughtNFTs
);
/// @dev It is emitted when new address is added to whitelist
/// @param account Acounts on whitelist
event AddToWhitelist(address indexed account);
/// @dev It is emitted when address is removed from whitelist
/// @param account Accounts removed from whitelist
event RemoveFromWhitelist(address indexed account);
/// @dev it is emitted when raised funds will be withdrawn
/// @param caller Address of administrator
/// @param amount Amount of withdrawn ETH
/// @param account Address of wallet where tokens were sent
event WithdrawFunds(address indexed caller, uint256 amount, address indexed account);
/// @dev user address => NFT collection address => amount of bought NFTs
mapping(address => mapping(address => uint256)) private boughtNFTs;
/// @dev NFT collection address => amount of sold NFTs
mapping(address => uint256) private soldNFTs;
/// @dev amount of available tokens per collection to buy by one wallet
uint8 public constant LIMIT_PER_USER = 3;
/// @dev user address => has access to buy
mapping(address => bool) private whitelist;
uint256 public whitelistedSaleStart;
uint256 public publicSaleStart;
uint256 public saleEnd;
/// @dev Contructor of sales contract
/// @param administrator Address of administrator's wallet
/// @param _whitelistedSaleStart Timestamp of whitelisted start sale
/// @param _publicSaleStart Timestamp of start public sale
/// @param _saleEnd Timestamp of end sale
constructor(
address administrator,
uint256 _whitelistedSaleStart,
uint256 _publicSaleStart,
uint256 _saleEnd
) {
_grantRole(DEFAULT_ADMIN_ROLE, administrator);
whitelistedSaleStart = _whitelistedSaleStart;
publicSaleStart = _publicSaleStart;
saleEnd = _saleEnd;
}
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Only for admin");
_;
}
/// @dev Function to buy tokens from NFT collections
/// @param nftCollection Address of NFT collection contract
/// @param nftsAmount Amount NFTs to buy
function buyNFT(FEEVMembershipNFT nftCollection, uint256 nftsAmount) external payable {
validateAccessToSale(msg.sender);
require(nftsAmount > 0, "Invalid NFTs amount");
require(
getBoughtNFTs(msg.sender, address(nftCollection)) + nftsAmount <= LIMIT_PER_USER,
"Tokens limit per collection (3) is reached by user"
);
uint256 nftSupply = nftCollection.totalSupply();
uint256 nftMaxSupply = nftCollection.maxSupply();
require(nftSupply + nftsAmount <= nftMaxSupply, "NFT max supply limit is reached");
uint256 price = nftCollection.getPrice(nftsAmount);
require(msg.value == price, "Insufficient ETH amount");
nftCollection.safeMint(msg.sender, nftsAmount);
boughtNFTs[msg.sender][address(nftCollection)] += nftsAmount;
soldNFTs[address(nftCollection)] += nftsAmount;
emit Purchase(msg.sender, address(nftCollection), price, nftsAmount);
}
/// @dev Getter for bought nft from given collection by user
/// @param user Address of user
/// @param nftCollectionAddress Address of NFT collection contract
/// @return uint256 Amount of bought NFTs
function getBoughtNFTs(address user, address nftCollectionAddress) public view returns (uint256) {
return boughtNFTs[user][nftCollectionAddress];
}
/// @dev Getter for total amount of sold NFT from specific collection
/// @param nftCollectionAddress Address of NFT collection contract
/// @return uint256 Amount of sold NFTs
function getSoldNFTs(address nftCollectionAddress) external view returns (uint256) {
return soldNFTs[nftCollectionAddress];
}
/// @dev Function to withdraw raised funds
/// @param account Address of wallet where tokens will be sent
/// @param amount Amount of token to withdraw
/// @notice It can be called only by administrator
function withdrawFunds(address account, uint256 amount) external onlyAdmin {
uint256 balance = address(this).balance;
require(balance >= amount, "Insufficient balance on sales contract");
(bool success, ) = payable(account).call{value: amount}("");
require(success, "Failed to sent ETH");
emit WithdrawFunds(msg.sender, amount, account);
}
/// @dev Function to set whitelisted sale start
/// @param start Timestamp of whitelisted sale start date
/// @notice It can be called only by administrator
function setWhitelistedSaleStart(uint256 start) external onlyAdmin {
require(start > block.timestamp, "The date needs to be future");
require(start < publicSaleStart, "The date needs to be before public sale start");
whitelistedSaleStart = start;
}
/// @dev Function to set public sale start
/// @param start Timestamp of public sale start date
/// @notice It can be called only by administrator
function setPublicSaleStart(uint256 start) external onlyAdmin {
require(start > block.timestamp, "The date needs to be future");
require(
start > whitelistedSaleStart,
"The date needs to be after start date of whitelisted sale"
);
require(start < saleEnd, "The date needs to be before public sale end");
publicSaleStart = start;
}
/// @dev Function to set sale end date
/// @param end Timestamp of end sale date
/// @notice It can be called only by administrator
function setSaleEnd(uint256 end) external onlyAdmin {
require(end > block.timestamp, "The date needs to be future");
require(end > publicSaleStart, "The date needs to be after start date of public sale");
saleEnd = end;
}
/// @dev Checking is wallet address is on the whitelist or have at least one NFT from defined collections
/// @param _address particular wallet address
function isWhitelisted(address _address) public view returns (bool) {
if (
whitelist[_address] ||
IERC721(0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D).balanceOf(_address) > 0 || // Bored Ape Yacht Club
IERC721(0x60E4d786628Fea6478F785A6d7e704777c86a7c6).balanceOf(_address) > 0 || // Mutant Ape Yacht Club
IERC721(0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB).balanceOf(_address) > 0 || // Crypto Punks
IERC721(0x3598Fff0f78Dd8b497e12a3aD91FeBcFC8F49d9E).balanceOf(_address) > 0 || // Private Jet Pyjama Party
IERC721(0xe785E82358879F061BC3dcAC6f0444462D4b5330).balanceOf(_address) > 0 || // World of Women
IERC721(0x75E95ba5997Eb235F40eCF8347cDb11F18ff640B).balanceOf(_address) > 0 || // Psychedelics Anonymous
IERC1155(0x28472a58A490c5e09A238847F66A68a47cC76f0f).balanceOf(_address, 0) > 0 // Adidas Originals Into the Metaverse
) {
return true;
}
return false;
}
/// @dev Adding array of addresses to whitelist
/// @param addresses array of addresses
/// @notice It can be called only by admin
function addToWhitelist(address[] memory addresses) public onlyAdmin {
for (uint16 i = 0; i < addresses.length; i++) {
if (!whitelist[addresses[i]]) {
whitelist[addresses[i]] = true;
emit AddToWhitelist(addresses[i]);
}
}
}
/// @dev Remove array of addresses from whitelist
/// @param addresses array of addresses
/// @notice It can be called only by admin
function removeFromWhitelist(address[] memory addresses) public onlyAdmin {
for (uint16 i = 0; i < addresses.length; i++) {
if (whitelist[addresses[i]]) {
whitelist[addresses[i]] = false;
emit RemoveFromWhitelist(addresses[i]);
}
}
}
function validateAccessToSale(address user) private view {
require(block.timestamp >= whitelistedSaleStart, "Sale is not opened");
require(block.timestamp <= saleEnd, "Sales is closed");
if (publicSaleStart > block.timestamp) {
require(isWhitelisted(user), "You are not whitelisted to buy NFT");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "./FeevieNFT.sol";
contract FEEVMembershipNFT is AccessControl, ERC721, ERC721Enumerable, IERC2981 {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
uint256 private constant INITIAL_MINT_LIMIT = 130;
string public baseURI;
uint256 public maxSupply;
uint256[] public priceRanges;
uint256[] public prices;
address public feevieNFT;
address private royaltyReceiver;
uint256 private royaltyBPS;
address private initialMintRecipient;
uint256 private amountOfInitiallyMintedTokens;
address public owner;
constructor(
string memory _name,
string memory _symbol,
address _owner,
address _minter,
address _initialMintRecipient,
uint256 _maxSupply,
address _royaltyReceiver,
string memory _initialURI,
address _feevieNFT,
uint256[] memory _priceRanges,
uint256[] memory _prices
) ERC721(_name, _symbol) {
maxSupply = _maxSupply;
_tokenIdCounter.increment();
_grantRole(DEFAULT_ADMIN_ROLE, _owner);
_grantRole(MINTER_ROLE, _owner);
_grantRole(MINTER_ROLE, _minter);
baseURI = _initialURI;
royaltyBPS = 800;
royaltyReceiver = _royaltyReceiver;
priceRanges = _priceRanges;
prices = _prices;
feevieNFT = _feevieNFT;
initialMintRecipient = _initialMintRecipient;
owner = _owner;
FeevieNFT(feevieNFT).setMembershipNFT(address(this));
}
/// @dev Function to mint initial amount of tokens to the feev.eth
/// @param amount Amount of tokens to mint
/// @notice It is possible to mint only 130 tokens
function initialMint(uint256 amount) external {
require(amountOfInitiallyMintedTokens + amount <= INITIAL_MINT_LIMIT, "Reached limit for minting");
for (uint256 i = 0; i < amount; i++) {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(initialMintRecipient, tokenId);
}
FeevieNFT(feevieNFT).safeMint(initialMintRecipient, amount);
amountOfInitiallyMintedTokens += amount;
}
/// @dev Function to mint new NFT tokens
/// @param to Address of new NFTs' owner
/// @param tokensAmount Amount of NFTs to mint
/// @notice It can be called only by address with minter role
function safeMint(address to, uint256 tokensAmount) public onlyRole(MINTER_ROLE) {
require(_tokenIdCounter.current() + tokensAmount <= maxSupply, "Reached limit for minting");
for (uint256 i = 0; i < tokensAmount; i++) {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
}
FeevieNFT(feevieNFT).safeMint(to, tokensAmount);
}
/// @dev Change owner address
/// @param newOwner Address of new owner
function changeOwner(address newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) {
owner = newOwner;
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
_revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// @dev Change baseURI
/// @param newURI New uri to new folder with metadata
/// @notice It can be called only by owner
function setBaseURI(string memory newURI) public onlyRole(DEFAULT_ADMIN_ROLE) {
baseURI = newURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/// @dev Function to set new royalties for each NFT token in the collection
/// @param _royaltyBPS Royalty amount in BPS (0 - 0%, 100% - 10000)
/// @param _royaltyReceiver Address of royalty receiver
/// @notice It can be called only by administrator
function setRoyalties(uint256 _royaltyBPS, address _royaltyReceiver)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
royaltyBPS = _royaltyBPS;
royaltyReceiver = _royaltyReceiver;
}
/// @dev Getter for info about royalty
/// @param tokenId Id of NFT token
/// @param salePrice Price to calculate royalty
/// @return receiver Address of royalty receiver
/// @return royaltyAmount Amount of calculated royalty
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
uint256 price = (salePrice * royaltyBPS) / 10000;
return (royaltyReceiver, price);
}
/// @dev Getter for price of minting
/// @param tokensAmount Amount of NFT tokens to mint
/// @return uint256 calculated price of minting
function getPrice(uint256 tokensAmount) external view returns (uint256) {
uint256 currentSupply = totalSupply();
uint256 price = 0;
for (
uint256 tokenNumber = currentSupply + 1;
tokenNumber <= currentSupply + tokensAmount;
tokenNumber++
) {
for (uint256 rangeIndex = 0; rangeIndex < priceRanges.length; rangeIndex++) {
if (tokenNumber > priceRanges[rangeIndex]) {
continue;
} else {
price += prices[rangeIndex];
break;
}
}
}
return price;
}
function isApprovedForAll(address _owner, address _operator)
public
view
override
returns (bool isOperator)
{
if (_operator == feevieNFT) {
return true;
}
return super.isApprovedForAll(_owner, _operator);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
super.transferFrom(from, to, tokenId);
FeevieNFT(feevieNFT).onMembershipNFTTransfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
super.safeTransferFrom(from, to, tokenId, "");
FeevieNFT(feevieNFT).onMembershipNFTTransfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
super.safeTransferFrom(from, to, tokenId, _data);
FeevieNFT(feevieNFT).onMembershipNFTTransfer(from, to, tokenId);
}
/// @dev Hook which is called on Feevie contract after Feevie token transfer
function onFeevieTransfer(
address from,
address to,
uint256 tokenId
) external {
require(msg.sender == feevieNFT, "Only for feevie contract");
super._transfer(from, to, tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(_exists(tokenId), "ERC721: nonexistent token");
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, IERC165, AccessControl)
returns (bool)
{
if (interfaceId == type(IERC2981).interfaceId) {
return true;
}
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "./FEEVMembershipNFT.sol";
contract FeevieNFT is AccessControl, ERC721, ERC721Enumerable, IERC2981 {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
string public baseURI;
address public owner;
address public membershipNFT;
uint256 private royaltyBPS;
address private royaltyReceiver;
constructor(
string memory _name,
string memory _symbol,
address _owner,
address _royaltyReceiver,
string memory _initialURI
) ERC721(_name, _symbol) {
_tokenIdCounter.increment();
_grantRole(DEFAULT_ADMIN_ROLE, _owner);
baseURI = _initialURI;
royaltyBPS = 800;
royaltyReceiver = _royaltyReceiver;
owner = _owner;
}
/// @dev Function to mint new NFT tokens
/// @param to Address of new NFTs' owner
/// @param tokensAmount Amount of NFTs to mint
/// @notice It can be called only by address with minter role
function safeMint(address to, uint256 tokensAmount) public onlyRole(MINTER_ROLE) {
for (uint256 i = 0; i < tokensAmount; i++) {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
}
}
/// @dev Change owner address
/// @param newOwner Address of new owner
function changeOwner(address newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) {
owner = newOwner;
_grantRole(DEFAULT_ADMIN_ROLE, newOwner);
_revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// @dev Change baseURI
/// @param newURI New uri to new folder with metadata
/// @notice It can be called only by owner
function setBaseURI(string memory newURI) public onlyRole(DEFAULT_ADMIN_ROLE) {
baseURI = newURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/// @dev Function to set new royalties for each NFT token in the collection
/// @param _royaltyBPS Royalty amount in BPS (0 - 0%, 100% - 10000)
/// @param _royaltyReceiver Address of royalty receiver
/// @notice It can be called only by administrator
function setRoyalties(uint256 _royaltyBPS, address _royaltyReceiver)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
royaltyBPS = _royaltyBPS;
royaltyReceiver = _royaltyReceiver;
}
/// @dev Getter for info about royalty
/// @param tokenId Id of NFT token
/// @param salePrice Price to calculate royalty
/// @return receiver Address of royalty receiver
/// @return royaltyAmount Amount of calculated royalty
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
uint256 price = (salePrice * royaltyBPS) / 10000;
return (royaltyReceiver, price);
}
/// @dev Function to set connected FEEV MC NFT contract
/// @param _membershipNFT Address of FEEV MC NFT contract
/// @notice Address can be set once
function setMembershipNFT(address _membershipNFT) external {
require(membershipNFT == address(0), "MembershipNFT is already set");
_grantRole(MINTER_ROLE, _membershipNFT);
membershipNFT = _membershipNFT;
}
function isApprovedForAll(address _owner, address _operator)
public
view
override
returns (bool isOperator)
{
if (_operator == membershipNFT) {
return true;
}
return super.isApprovedForAll(_owner, _operator);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
super.transferFrom(from, to, tokenId);
FEEVMembershipNFT(membershipNFT).onFeevieTransfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
super.safeTransferFrom(from, to, tokenId, "");
FEEVMembershipNFT(membershipNFT).onFeevieTransfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
super.safeTransferFrom(from, to, tokenId, _data);
FEEVMembershipNFT(membershipNFT).onFeevieTransfer(from, to, tokenId);
}
/// @dev Hook which is called on FEEV MC contract after MC token transfer
function onMembershipNFTTransfer(
address from,
address to,
uint256 tokenId
) external {
require(msg.sender == membershipNFT, "Only for membership NFT contract");
super._transfer(from, to, tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(_exists(tokenId), "ERC721: nonexistent token");
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, IERC165, AccessControl)
returns (bool)
{
if (interfaceId == type(IERC2981).interfaceId) {
return true;
}
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
|
Getter for total amount of sold NFT from specific collection nftCollectionAddress Address of NFT collection contract return uint256 Amount of sold NFTs
|
function getSoldNFTs(address nftCollectionAddress) external view returns (uint256) {
return soldNFTs[nftCollectionAddress];
}
| 12,191,755
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @dev Interface to C-folio item contracts
*/
interface IBooster {
/**
* @dev Return information about the reward state in Booster
*
* @param tokenIds The SFT or TF tokenId
*
* @return locked The total amounts locked
* @return pending The pending amounts claimable
* @return apr The APR of this lock pool
* @return secsLeft Numbers of seconds until unlock, or -1 if unlocked
*/
function getRewardInfo(uint256[] calldata tokenIds)
external
view
returns (
uint256[] memory locked,
uint256[] memory pending,
uint256[] memory apr,
uint256[] memory secsLeft
);
/**
* @dev Handles farm distribution, only callable from controller
*
* If recipient is booster contract, amount is temporarily stored and locked
* in a second call.
*
* @param farm The reward farm that the call originates from
* @param recipient The recipient of the rewards
* @param amount The amount to distribute
* @param fee The fee in 6 decimal notation
*/
function distributeFromFarm(
address farm,
address recipient,
uint256 amount,
uint32 fee
) external;
/**
* @dev Locks temporary tokens owned by recipient for a specific duration
* of seconds.
*
* @param recipient The recipient of the rewards
* @param lockPeriod The lock period in seconds
*/
function lock(address recipient, uint256 lockPeriod) external;
/**
* @dev Claim rewards either into wallet or re-lock them
*
* @param sftTokenId The tokenId that manages the rewards
* @param reLock True to re-lock existing rewards to earn more
*/
function claimRewards(uint256 sftTokenId, bool reLock) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity 0.7.6;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '../booster/interfaces/IBooster.sol';
import '../utils/AddressBook.sol';
import '../utils/interfaces/IAddressRegistry.sol';
import './interfaces/IController.sol';
import './interfaces/IFarm.sol';
contract Controller is IController, Context, Ownable {
using SafeMath for uint256;
//////////////////////////////////////////////////////////////////////////////
// Routing
//////////////////////////////////////////////////////////////////////////////
IBooster private immutable _booster;
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
// We need the previous controller for calculation of pending rewards
address public previousController;
// The address which is alowed to call service functions
address public worker;
address private farmHead;
struct Farm {
address nextFarm;
uint256 farmStartedAtBlock;
uint256 farmEndedAtBlock;
uint256 rewardCap;
uint256 rewardProvided;
uint256 rewardPerDuration;
uint32 rewardFee;
bool paused;
bool active;
}
mapping(address => Farm) public farms;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
event FarmRegistered(address indexed farm);
event FarmUpdated(address indexed farm);
event FarmDisabled(address indexed farm);
event FarmPaused(address indexed farm, bool pause);
event FarmTransfered(address indexed farm, address indexed to);
event Rebalanced(address indexed farm);
event Refueled(address indexed farm, uint256 amount);
//////////////////////////////////////////////////////////////////////////////
// Modifiers
//////////////////////////////////////////////////////////////////////////////
modifier onlyWorker() {
require(_msgSender() == worker, 'not worker');
_;
}
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev rewardHandler is the instance which finally stores the reward token
* and distributes them to the different recipients
*
* @param _addressRegistry IAdressRegistry to get system addresses
* @param _previousController The previous controller
*/
constructor(IAddressRegistry _addressRegistry, address _previousController) {
// Initialize state
previousController = _previousController;
// Proxied booster address / immutable
_booster = IBooster(
_addressRegistry.getRegistryEntry(AddressBook.WOWS_BOOSTER_PROXY)
);
// Initialize {Ownable}
address _marketingWallet = _addressRegistry.getRegistryEntry(
AddressBook.MARKETING_WALLET
);
transferOwnership(_marketingWallet);
}
//////////////////////////////////////////////////////////////////////////////
// Routing
//////////////////////////////////////////////////////////////////////////////
function setWorker(address _worker) external onlyOwner {
worker = _worker;
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {IController}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {IController-onDeposit}
*/
function onDeposit(
uint256 /* amount*/
) external view override returns (uint256 fee) {
// Load state
Farm storage farm = farms[_msgSender()];
// Validate state
require(farm.farmStartedAtBlock > 0, 'Caller not a farm');
require(farm.farmEndedAtBlock == 0, 'Farm closed');
require(!farm.paused, 'Farm paused');
return 0;
}
/**
* @dev See {IController-onDeposit}
*/
function onWithdraw(
uint256 /* amount*/
) external view override returns (uint256 fee) {
// Validate state
require(!farms[_msgSender()].paused, 'Farm paused');
return 0;
}
/**
* @dev See {IController-payOutRewards}
*/
function payOutRewards(address recipient, uint256 amount) external override {
// Load state
Farm storage farm = farms[_msgSender()];
// Validate state
require(farm.farmStartedAtBlock > 0, 'Caller not a farm');
require(recipient != address(0), 'Recipient 0 address');
require(!farm.paused, 'Farm paused');
require(
amount.add(farm.rewardProvided) <= farm.rewardCap,
'Reward cap reached'
);
// Update state
_booster.distributeFromFarm(
_msgSender(),
recipient,
amount,
farm.rewardFee
);
}
//////////////////////////////////////////////////////////////////////////////
// Farm management
//////////////////////////////////////////////////////////////////////////////
/**
* @dev registerFarm can be called from outside (for new Farms deployed with
* this controller) or from transferFarm() call
*
* Contracts are active from the time of registering, but to provide rewards,
* refuelFarms must be called (for new Farms / due Farms).
*
* Use this function also for updating reward parameters and / or fee.
* _rewardProvided should be left 0, it is mainly used if a farm is
* transferred.
*
* @param _farmAddress Contract address of farm
* @param _rewardCap Maximum amount of tokens rewardable
* @param _rewardPerDuration Refuel amount of tokens, duration is fixed in
* farm contract
* @param _rewardProvided Already provided rewards for this farm, should be 0
* for external calls
* @param _rewardFee Fee we take from the reward and distribute through
* components (1e6 factor)
*/
function registerFarm(
address _farmAddress,
uint256 _rewardCap,
uint256 _rewardPerDuration,
uint256 _rewardProvided,
uint32 _rewardFee
) external {
// Validate access
require(
_msgSender() == owner() || _msgSender() == previousController,
'Not allowed'
);
// Validate parameters
require(_farmAddress != address(0), 'Invalid farm (0)');
require(IFarm(_farmAddress).controller() == this, 'Invalid farm (C)');
// Farm existent, add new reward logic
Farm storage farm = farms[_farmAddress];
if (farm.farmStartedAtBlock > 0) {
// Re-enable farm if disabled
farm.farmEndedAtBlock = 0;
farm.paused = false;
farm.active = true;
farm.rewardCap = _rewardCap;
farm.rewardFee = _rewardFee;
farm.rewardPerDuration = _rewardPerDuration;
if (_rewardProvided > 0) farm.rewardProvided = _rewardProvided;
// Dispatch event
emit FarmUpdated(_farmAddress);
}
// We have a new farm
else {
// If we have one with same name, deactivate old one
bytes32 farmName = keccak256(
abi.encodePacked(IFarm(_farmAddress).farmName())
);
address searchAddress = farmHead;
while (
searchAddress != address(0) &&
farmName != keccak256(abi.encodePacked(IFarm(searchAddress).farmName()))
) searchAddress = farms[searchAddress].nextFarm;
// If found (update), disable existing farm
if (searchAddress != address(0)) {
farms[searchAddress].farmEndedAtBlock = block.number;
_rewardProvided = farms[searchAddress].rewardProvided;
}
// Insert the new Farm
farm.nextFarm = farmHead;
farm.farmStartedAtBlock = block.number;
farm.farmEndedAtBlock = 0;
farm.rewardCap = _rewardCap;
farm.rewardProvided = _rewardProvided;
farm.rewardPerDuration = _rewardPerDuration;
farm.rewardFee = _rewardFee;
farm.paused = false;
farm.active = true;
farmHead = _farmAddress;
// Dispatch event
emit FarmRegistered(_farmAddress);
}
}
/**
* @dev Note that disabled farms can only be enabled again by calling
* registerFarm() with new parameters
*
* This function is meant to finally end a farm.
*
* @param _farmAddress Contract address of farm to disable
*/
function disableFarm(address _farmAddress) external onlyOwner {
// Load state
Farm storage farm = farms[_farmAddress];
// Validate state
require(farm.farmStartedAtBlock > 0, 'Not a farm');
// Update state
farm.farmEndedAtBlock = block.number;
// Dispatch event
emit FarmDisabled(_farmAddress);
_checkActive(farm);
}
/**
* @dev This is an emergency pause, which should be called in case of serious
* issues.
*
* Deposit / withdraw and rewards are disabled while pause is set to true.
*
* @param _farmAddress Contract address of farm to pause
* @param _pause To pause / unpause a farm
*/
function pauseFarm(address _farmAddress, bool _pause) external onlyOwner {
// Load state
Farm storage farm = farms[_farmAddress];
// Validate state
require(farm.farmStartedAtBlock > 0, 'Not a farm');
// Update state
farm.paused = _pause;
// Dispatch event
emit FarmPaused(_farmAddress, _pause);
_checkActive(farm);
}
/**
* @dev Transfer farm to a new controller
*
* @param _farmAddress Contract address of farm to transfer
* @param _newController The new controller which receives the farm
*/
function transferFarm(address _farmAddress, address _newController)
public
onlyOwner
{
// Validate parameters
require(_newController != address(0), 'newController = 0');
require(_newController != address(this), 'newController = this');
// Load state
Farm storage farm = farms[_farmAddress];
// Validate state
require(farm.farmStartedAtBlock > 0, 'Farm not registered');
// Update state
IFarm(_farmAddress).setController(_newController);
// Register this farm in the new controller
Controller(_newController).registerFarm(
_farmAddress,
farm.rewardCap,
farm.rewardPerDuration,
farm.rewardProvided,
farm.rewardFee
);
// Remove this farm from controller
if (_farmAddress == farmHead) {
farmHead = farm.nextFarm;
} else {
address searchAddress = farmHead;
while (farms[searchAddress].nextFarm != _farmAddress)
searchAddress = farms[searchAddress].nextFarm;
farms[searchAddress].nextFarm = farm.nextFarm;
}
delete (farms[_farmAddress]);
// Dispatch event
emit FarmTransfered(_farmAddress, _newController);
}
/**
* @dev Transfer all existing farms to a new controller
*
* @param _newController The new controller which receives the farms
*/
function transferAllFarms(address _newController) external onlyOwner {
while (farmHead != address(0)) {
transferFarm(farmHead, _newController);
}
}
/**
* @dev Change the reward duration in a Farm
*
* @param farmAddress Contract address of farm to change duration
* @param newDuration The new reward duration in seconds
*
* @notice In general a farm has to be in finished state to be able
* to change the duration
*/
function setFarmRewardDuration(address farmAddress, uint256 newDuration)
external
onlyOwner
{
// Validate parameters
require(IFarm(farmAddress).controller() == this, 'Invalid farm (C)');
// Update state
IFarm(farmAddress).setRewardsDuration(newDuration);
}
//////////////////////////////////////////////////////////////////////////////
// Utility functions
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Allows rebalancing assets inside a farm
*
* There is currently no active implementation.
*/
function rebalance() external onlyWorker {
// Update state
address iterAddress = farmHead;
while (iterAddress != address(0)) {
if (farms[iterAddress].active) {
IFarm(iterAddress).rebalance();
}
iterAddress = farms[iterAddress].nextFarm;
}
// Dispatch event
emit Rebalanced(iterAddress);
}
/**
* @dev Refuel all farms which will expire in the next hour
*
* By default the preconfigured rewardPerDuration is used, but can be
* overridden by rewards parameter.
*
* @notice If rewards parameer is provided, the value cannot exceed the
* preconfigured rewardPerDuration.
*
* @param addresses Addresses to be used instead rewardPerDuration
* @param rewards Amonts to be used instead rewardPerDuration
*/
function refuelFarms(address[] calldata addresses, uint256[] calldata rewards)
external
onlyWorker
{
// Validate parameters
require(addresses.length == rewards.length, 'C: Length mismatch');
address iterAddress = farmHead;
bool oneRefueled = false;
while (iterAddress != address(0)) {
// Refuel if farm end is one day ahead
Farm storage farm = farms[iterAddress];
if (
farm.active &&
// solhint-disable-next-line not-rely-on-time
block.timestamp + 3600 >= IFarm(iterAddress).periodFinish()
) {
uint256 i;
while (i < addresses.length && addresses[i] != iterAddress) ++i;
uint256 reward = (i < addresses.length &&
rewards[i] < farm.rewardPerDuration)
? rewards[i]
: farm.rewardPerDuration;
// Update state
IFarm(iterAddress).notifyRewardAmount(reward);
farm.rewardProvided = farm.rewardProvided.add(reward);
require(farm.rewardProvided <= farm.rewardCap, 'C: Cap reached');
// Dispatch event
emit Refueled(iterAddress, reward);
oneRefueled = true;
}
iterAddress = farm.nextFarm;
}
require(oneRefueled, 'NOP');
}
//////////////////////////////////////////////////////////////////////////////
// Implementation details
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Shortcut to check if a farm is active
*/
function _checkActive(Farm storage farm) internal {
farm.active = !(farm.paused || farm.farmEndedAtBlock > 0);
}
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity 0.7.6;
interface IController {
/**
* @dev Used to control fees and accessibility instead having an implementation
* in each farm contract
*
* Deposit is only allowed if farm is open and not not paused. Must revert on
* failure.
*
* @param amount Number of tokens the user wants to deposit
*
* @return fee The deposit fee (1e18 factor) on success
*/
function onDeposit(uint256 amount) external view returns (uint256 fee);
/**
* @dev Used to control fees and accessibility instead having an
* implementation in each farm contract
*
* Withdraw is only allowed if farm is not paused. Must revert on failure
*
* @param amount Number of tokens the user wants to withdraw
*
* @return fee The withdrawal fee (1e18 factor) on success
*/
function onWithdraw(uint256 amount) external view returns (uint256 fee);
/**
* @dev Distribute rewards to sender and fee to internal contracts
*/
function payOutRewards(address recipient, uint256 amount) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity 0.7.6;
import './IController.sol';
interface IFarm {
/**
* @dev Return the farm's controller
*/
function controller() external view returns (IController);
/**
* @dev Return a unique, case-sensitive farm name
*/
function farmName() external view returns (string memory);
/**
* @dev Return when reward period is finished (UTC timestamp)
*/
function periodFinish() external view returns (uint256);
/**
* @dev Return the rewards duration in seconds
*/
function rewardsDuration() external view returns (uint256);
/**
* @dev Sets a new controller, can only be called by current controller
*/
function setController(address newController) external;
/**
* @dev This function must be called initially and close at the time the
* reward period ends
*/
function notifyRewardAmount(uint256 reward) external;
/**
* @dev Set the duration of farm rewards, to continue rewards,
* notifyRewardAmount() has to called for the next period
*/
function setRewardsDuration(uint256 _rewardsDuration) external;
/**
* @dev Rebalance strategies (if implemented)
*/
function rebalance() external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library AddressBook {
bytes32 public constant DEPLOYER = 'DEPLOYER';
bytes32 public constant TEAM_WALLET = 'TEAM_WALLET';
bytes32 public constant MARKETING_WALLET = 'MARKETING_WALLET';
bytes32 public constant UNISWAP_V2_ROUTER02 = 'UNISWAP_V2_ROUTER02';
bytes32 public constant WETH_WOWS_STAKE_FARM = 'WETH_WOWS_STAKE_FARM';
bytes32 public constant WOWS_TOKEN = 'WOWS_TOKEN';
bytes32 public constant UNISWAP_V2_PAIR = 'UNISWAP_V2_PAIR';
bytes32 public constant WOWS_BOOSTER_PROXY = 'WOWS_BOOSTER_PROXY';
bytes32 public constant REWARD_HANDLER = 'REWARD_HANDLER';
bytes32 public constant SFT_MINTER = 'SFT_MINTER';
bytes32 public constant SFT_HOLDER = 'SFT_HOLDER';
bytes32 public constant CFOLIOITEM_BRIDGE_PROXY = 'CFOLIOITEM_BRIDGE_PROXY';
bytes32 public constant BOIS_REWARDS = 'BOIS_REWARDS';
bytes32 public constant WOLVES_REWARDS = 'WOLVES_REWARDS';
bytes32 public constant SFT_EVALUATOR_PROXY = 'SFT_EVALUATOR_PROXY';
bytes32 public constant TRADE_FLOOR_PROXY = 'TRADE_FLOOR_PROXY';
bytes32 public constant CURVE_Y_TOKEN = 'CURVE_Y_TOKEN';
bytes32 public constant CURVE_Y_DEPOSIT = 'CURVE_Y_DEPOSIT';
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
interface IAddressRegistry {
/**
* @dev Set an abitrary key / address pair into the registry
*/
function setRegistryEntry(bytes32 _key, address _location) external;
/**
* @dev Get a registry enty with by key, returns 0 address if not existing
*/
function getRegistryEntry(bytes32 _key) external view returns (address);
}
|
See {IController-payOutRewards}/ Load state Validate state Update state
|
function payOutRewards(address recipient, uint256 amount) external override {
Farm storage farm = farms[_msgSender()];
require(farm.farmStartedAtBlock > 0, 'Caller not a farm');
require(recipient != address(0), 'Recipient 0 address');
require(!farm.paused, 'Farm paused');
require(
amount.add(farm.rewardProvided) <= farm.rewardCap,
'Reward cap reached'
);
_booster.distributeFromFarm(
_msgSender(),
recipient,
amount,
farm.rewardFee
);
}
| 11,739,315
|
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "./ERC20/IERC20.sol";
import "./ERC20/IERC20Permit.sol";
import "./ERC20/SafeERC20.sol";
import "./interfaces/IERC3156FlashBorrower.sol";
import "./interfaces/IERC3156FlashLender.sol";
import "./interfaces/IRERC20.sol";
import "./interfaces/IRTokenProxy.sol";
import "./interfaces/IRulerCore.sol";
import "./interfaces/IOracle.sol";
import "./utils/Clones.sol";
import "./utils/Create2.sol";
import "./utils/Initializable.sol";
import "./utils/Ownable.sol";
import "./utils/ReentrancyGuard.sol";
/**
* @title RulerCore contract
* @author crypto-pumpkin
* Ruler Pair: collateral, paired token, expiry, mintRatio
* - ! Paired Token cannot be a deflationary token !
* - rTokens have same decimals of each paired token
* - all Ratios are 1e18
* - rTokens have same decimals as Paired Token
* - Collateral can be deflationary token, but not rebasing token
*/
contract RulerCore is Ownable, IRulerCore, IERC3156FlashLender, ReentrancyGuard {
using SafeERC20 for IERC20;
// following ERC3156 https://eips.ethereum.org/EIPS/eip-3156
bytes32 public constant FLASHLOAN_CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan");
bool public override paused;
IOracle public override oracle;
address public override responder;
address public override feeReceiver;
address public override rERC20Impl;
uint256 public override flashLoanRate;
address[] public override collaterals;
/// @notice collateral => minimum collateralization ratio, paired token default to 1e18
mapping(address => uint256) public override minColRatioMap;
/// @notice collateral => pairedToken => expiry => mintRatio => Pair
mapping(address => mapping(address => mapping(uint48 => mapping(uint256 => Pair)))) public override pairs;
mapping(address => Pair[]) private pairList;
mapping(address => uint256) public override feesMap;
// v1.0.2
uint256 public override depositPauseWindow;
// v1.0.3
uint256 public override redeemFeeRate;
modifier onlyNotPaused() {
require(!paused, "Ruler: paused");
_;
}
function initialize(address _rERC20Impl, address _feeReceiver) external initializer {
require(_rERC20Impl != address(0), "Ruler: _rERC20Impl cannot be 0");
require(_feeReceiver != address(0), "Ruler: _feeReceiver cannot be 0");
rERC20Impl = _rERC20Impl;
feeReceiver = _feeReceiver;
flashLoanRate = 0.00085 ether;
depositPauseWindow = 24 hours;
initializeOwner();
initializeReentrancyGuard();
}
/// @notice market make deposit, deposit paired Token to received rcTokens, considered as an immediately repaid loan
function mmDeposit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) public override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
_validateDepositInputs(_col, pair);
pair.rcToken.mint(msg.sender, _rcTokenAmt);
feesMap[_paired] = feesMap[_paired] + _rcTokenAmt * pair.feeRate / 1e18;
// record loan ammount to colTotal as it is equivalent to be an immediately repaid loan
uint256 colAmount = _getColAmtFromRTokenAmt(_rcTokenAmt, _col, address(pair.rcToken), pair.mintRatio);
pairs[_col][_paired][_expiry][_mintRatio].colTotal = pair.colTotal + colAmount;
// receive paired tokens from sender, deflationary token is not allowed
IERC20 pairedToken = IERC20(_paired);
uint256 pairedBalBefore = pairedToken.balanceOf(address(this));
pairedToken.safeTransferFrom(msg.sender, address(this), _rcTokenAmt);
require(pairedToken.balanceOf(address(this)) - pairedBalBefore >= _rcTokenAmt, "Ruler: transfer paired failed");
emit MarketMakeDeposit(msg.sender, _col, _paired, _expiry, _mintRatio, _rcTokenAmt);
}
function mmDepositWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt,
Permit calldata _pairedPermit
) external override {
_permit(_paired, _pairedPermit);
mmDeposit(_col, _paired, _expiry, _mintRatio, _rcTokenAmt);
}
/// @notice deposit collateral to a Ruler Pair, sender receives rcTokens and rrTokens
function deposit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _colAmt
) public override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
_validateDepositInputs(_col, pair);
// receive collateral
IERC20 collateral = IERC20(_col);
uint256 colBalBefore = collateral.balanceOf(address(this));
collateral.safeTransferFrom(msg.sender, address(this), _colAmt);
uint256 received = collateral.balanceOf(address(this)) - colBalBefore;
require(received > 0, "Ruler: transfer failed");
pairs[_col][_paired][_expiry][_mintRatio].colTotal = pair.colTotal + received;
// mint rTokens for reveiced collateral
uint256 mintAmount = _getRTokenAmtFromColAmt(received, _col, _paired, pair.mintRatio);
pair.rcToken.mint(msg.sender, mintAmount);
pair.rrToken.mint(msg.sender, mintAmount);
emit Deposit(msg.sender, _col, _paired, _expiry, _mintRatio, received);
}
function depositWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _colAmt,
Permit calldata _colPermit
) external override {
_permit(_col, _colPermit);
deposit(_col, _paired, _expiry, _mintRatio, _colAmt);
}
/// @notice redeem with rrTokens and rcTokens before expiry only, sender receives collateral, fees charged on collateral
function redeem(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rTokenAmt
) external override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
require(pair.mintRatio != 0, "Ruler: pair does not exist");
require(block.timestamp <= pair.expiry, "Ruler: expired, col forfeited");
pair.rrToken.burnByRuler(msg.sender, _rTokenAmt);
pair.rcToken.burnByRuler(msg.sender, _rTokenAmt);
// send collateral to sender
uint256 colAmountToPay = _getColAmtFromRTokenAmt(_rTokenAmt, _col, address(pair.rcToken), pair.mintRatio);
// once redeemed, it won't be considered as a loan for the pair anymore
pairs[_col][_paired][_expiry][_mintRatio].colTotal = pair.colTotal - colAmountToPay;
// accrue fees on payment
_sendAmtPostFeesOptionalAccrue(IERC20(_col), colAmountToPay, redeemFeeRate, true /* accrue */);
emit Redeem(msg.sender, _col, _paired, _expiry, _mintRatio, _rTokenAmt);
}
/// @notice repay with rrTokens and paired token amount, sender receives collateral, no fees charged on collateral
function repay(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rrTokenAmt
) public override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
require(pair.mintRatio != 0, "Ruler: pair does not exist");
require(block.timestamp <= pair.expiry, "Ruler: expired, col forfeited");
pair.rrToken.burnByRuler(msg.sender, _rrTokenAmt);
// receive paired tokens from sender, deflationary token is not allowed
IERC20 pairedToken = IERC20(_paired);
uint256 pairedBalBefore = pairedToken.balanceOf(address(this));
pairedToken.safeTransferFrom(msg.sender, address(this), _rrTokenAmt);
require(pairedToken.balanceOf(address(this)) - pairedBalBefore >= _rrTokenAmt, "Ruler: transfer paired failed");
feesMap[_paired] = feesMap[_paired] + _rrTokenAmt * pair.feeRate / 1e18;
// send collateral back to sender
uint256 colAmountToPay = _getColAmtFromRTokenAmt(_rrTokenAmt, _col, address(pair.rrToken), pair.mintRatio);
_safeTransfer(IERC20(_col), msg.sender, colAmountToPay);
emit Repay(msg.sender, _col, _paired, _expiry, _mintRatio, _rrTokenAmt);
}
function repayWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rrTokenAmt,
Permit calldata _pairedPermit
) external override {
_permit(_paired, _pairedPermit);
repay(_col, _paired, _expiry, _mintRatio, _rrTokenAmt);
}
/// @notice sender collect paired tokens by returning same amount of rcTokens to Ruler
function collect(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) external override onlyNotPaused nonReentrant {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
require(pair.mintRatio != 0, "Ruler: pair does not exist");
require(block.timestamp > pair.expiry, "Ruler: not ready");
pair.rcToken.burnByRuler(msg.sender, _rcTokenAmt);
IERC20 pairedToken = IERC20(_paired);
uint256 defaultedLoanAmt = pair.rrToken.totalSupply();
if (defaultedLoanAmt == 0) { // no default, send paired Token to sender
// no fees accrued as it is accrued on Borrower payment
_sendAmtPostFeesOptionalAccrue(pairedToken, _rcTokenAmt, pair.feeRate, false /* accrue */);
} else {
// rcTokens eligible to collect at expiry (converted from total collateral received, redeemed collateral not counted) == total loan amount at the moment of expiry
uint256 rcTokensEligibleAtExpiry = _getRTokenAmtFromColAmt(pair.colTotal, _col, _paired, pair.mintRatio);
// paired token amount to pay = rcToken amount * (1 - default ratio)
uint256 pairedTokenAmtToCollect = _rcTokenAmt * (rcTokensEligibleAtExpiry - defaultedLoanAmt) / rcTokensEligibleAtExpiry;
// no fees accrued as it is accrued on Borrower payment
_sendAmtPostFeesOptionalAccrue(pairedToken, pairedTokenAmtToCollect, pair.feeRate, false /* accrue */);
// default collateral amount to pay = converted collateral amount (from rcTokenAmt) * default ratio
uint256 colAmount = _getColAmtFromRTokenAmt(_rcTokenAmt, _col, address(pair.rcToken), pair.mintRatio);
uint256 colAmountToCollect = colAmount * defaultedLoanAmt / rcTokensEligibleAtExpiry;
// accrue fees on defaulted collateral since it was never accrued
_sendAmtPostFeesOptionalAccrue(IERC20(_col), colAmountToCollect, pair.feeRate, true /* accrue */);
}
emit Collect(msg.sender, _col, _paired,_expiry, _mintRatio, _rcTokenAmt);
}
function collectFees(IERC20[] calldata _tokens) external override onlyOwner {
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20 token = _tokens[i];
uint256 fee = feesMap[address(token)];
feesMap[address(token)] = 0;
_safeTransfer(token, feeReceiver, fee);
}
}
/**
* @notice add a new Ruler Pair
* - Paired Token cannot be a deflationary token
* - minColRatio is not respected if collateral is alreay added
* - all Ratios are 1e18
*/
function addPair(
address _col,
address _paired,
uint48 _expiry,
string calldata _expiryStr,
uint256 _mintRatio,
string calldata _mintRatioStr,
uint256 _feeRate
) external override onlyOwner {
require(pairs[_col][_paired][_expiry][_mintRatio].mintRatio == 0, "Ruler: pair exists");
require(_mintRatio > 0, "Ruler: _mintRatio <= 0");
require(_feeRate < 0.1 ether, "Ruler: fee rate must be < 10%");
require(_expiry > block.timestamp, "Ruler: expiry in the past");
require(minColRatioMap[_col] > 0, "Ruler: col not listed");
if (minColRatioMap[_paired] == 0) {
collaterals.push(_paired); // auto add paired token to collateral list
minColRatioMap[_paired] = 1.05 ether; // default paired token to 105% collateralization ratio as most of them are stablecoins, can be updated later.
}
Pair memory pair = Pair({
active: true,
feeRate: _feeRate,
mintRatio: _mintRatio,
expiry: _expiry,
pairedToken: _paired,
rcToken: IRERC20(_createRToken(_col, _paired, _expiry, _expiryStr, _mintRatioStr, "RC_")),
rrToken: IRERC20(_createRToken(_col, _paired, _expiry, _expiryStr, _mintRatioStr, "RR_")),
colTotal: 0
});
pairs[_col][_paired][_expiry][_mintRatio] = pair;
pairList[_col].push(pair);
emit PairAdded(_col, _paired, _expiry, _mintRatio);
}
/**
* @notice allow flash loan borrow allowed tokens up to all core contracts' holdings
* _receiver will received the requested amount, and need to payback the loan amount + fees
* _receiver must implement IERC3156FlashBorrower
* no deflationary tokens
*/
function flashLoan(
IERC3156FlashBorrower _receiver,
address _token,
uint256 _amount,
bytes calldata _data
) public override onlyNotPaused returns (bool) {
require(minColRatioMap[_token] > 0, "Ruler: token not allowed");
IERC20 token = IERC20(_token);
uint256 tokenBalBefore = token.balanceOf(address(this));
token.safeTransfer(address(_receiver), _amount);
uint256 fees = flashFee(_token, _amount);
require(
_receiver.onFlashLoan(msg.sender, _token, _amount, fees, _data) == FLASHLOAN_CALLBACK_SUCCESS,
"IERC3156: Callback failed"
);
// receive loans and fees
token.safeTransferFrom(address(_receiver), address(this), _amount + fees);
require(token.balanceOf(address(this)) - tokenBalBefore >= fees, "Ruler: not enough fees");
feesMap[_token] = feesMap[_token] + fees;
emit FlashLoan(_token, address(_receiver), _amount);
return true;
}
/// @notice flashloan rate can be anything
function setFlashLoanRate(uint256 _newRate) external override onlyOwner {
emit FlashLoanRateUpdated(flashLoanRate, _newRate);
flashLoanRate = _newRate;
}
/// @notice add new or update existing collateral
function updateCollateral(address _col, uint256 _minColRatio) external override onlyOwner {
require(_minColRatio > 0, "Ruler: min colRatio < 0");
emit CollateralUpdated(_col, minColRatioMap[_col], _minColRatio);
if (minColRatioMap[_col] == 0) {
collaterals.push(_col);
}
minColRatioMap[_col] = _minColRatio;
}
function setPairActive(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
bool _active
) external override onlyOwner {
pairs[_col][_paired][_expiry][_mintRatio].active = _active;
}
function setFeeReceiver(address _address) external override onlyOwner {
require(_address != address(0), "Ruler: address cannot be 0");
emit AddressUpdated('feeReceiver', feeReceiver, _address);
feeReceiver = _address;
}
/// @dev update this will only affect pools deployed after
function setRERC20Impl(address _newImpl) external override onlyOwner {
require(_newImpl != address(0), "Ruler: _newImpl cannot be 0");
emit RERC20ImplUpdated(rERC20Impl, _newImpl);
rERC20Impl = _newImpl;
}
function setPaused(bool _paused) external override {
require(msg.sender == owner() || msg.sender == responder, "Ruler: not owner/responder");
emit PausedStatusUpdated(paused, _paused);
paused = _paused;
}
function setResponder(address _address) external override onlyOwner {
require(_address != address(0), "Ruler: address cannot be 0");
emit AddressUpdated('responder', responder, _address);
responder = _address;
}
function setOracle(address _address) external override onlyOwner {
require(_address != address(0), "Ruler: address cannot be 0");
emit AddressUpdated('oracle', address(oracle), _address);
oracle = IOracle(_address);
}
/// @notice flashloan rate can be anything
function setDepositPauseWindow(uint256 _newWindow) external override onlyOwner {
emit DepositPauseWindow(depositPauseWindow, _newWindow);
depositPauseWindow = _newWindow;
}
/// @notice redeemFee rate can be anything < 10%
function setRedeemFeeRate(uint256 _newFeeRate) external override onlyOwner {
require(_newFeeRate < 0.1 ether, "Ruler: fee rate must be < 10%");
emit RedeemFeeRateUpdated(redeemFeeRate, _newFeeRate);
redeemFeeRate = _newFeeRate;
}
function getCollaterals() external view override returns (address[] memory) {
return collaterals;
}
function getPairList(address _col) external view override returns (Pair[] memory) {
Pair[] memory colPairList = pairList[_col];
Pair[] memory _pairs = new Pair[](colPairList.length);
for (uint256 i = 0; i < colPairList.length; i++) {
Pair memory pair = colPairList[i];
_pairs[i] = pairs[_col][pair.pairedToken][pair.expiry][pair.mintRatio];
}
return _pairs;
}
/// @notice amount that is eligible to collect
function viewCollectible(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) external view override returns (uint256 colAmtToCollect, uint256 pairedAmtToCollect) {
Pair memory pair = pairs[_col][_paired][_expiry][_mintRatio];
if (pair.mintRatio == 0 || block.timestamp < pair.expiry) return (colAmtToCollect, pairedAmtToCollect);
uint256 defaultedLoanAmt = pair.rrToken.totalSupply();
if (defaultedLoanAmt == 0) { // no default, transfer paired Token
pairedAmtToCollect = _rcTokenAmt;
} else {
// rcTokens eligible to collect at expiry (converted from total collateral received, redeemed collateral not counted) == total loan amount at the moment of expiry
uint256 rcTokensEligibleAtExpiry = _getRTokenAmtFromColAmt(pair.colTotal, _col, _paired, pair.mintRatio);
// paired token amount to pay = rcToken amount * (1 - default ratio)
pairedAmtToCollect = _rcTokenAmt * (rcTokensEligibleAtExpiry - defaultedLoanAmt) * (1e18 - pair.feeRate) / 1e18 / rcTokensEligibleAtExpiry;
// default collateral amount to pay = converted collateral amount (from rcTokenAmt) * default ratio
uint256 colAmount = _getColAmtFromRTokenAmt(_rcTokenAmt, _col, address(pair.rcToken), pair.mintRatio);
colAmtToCollect = colAmount * defaultedLoanAmt * (1e18 - pair.feeRate) / 1e18 / rcTokensEligibleAtExpiry;
}
}
function maxFlashLoan(address _token) external view override returns (uint256) {
return IERC20(_token).balanceOf(address(this));
}
/// @notice returns the amount of fees charges by for the loan amount. 0 means no fees charged, may not have the token
function flashFee(address _token, uint256 _amount) public view override returns (uint256 _fees) {
require(minColRatioMap[_token] > 0, "RulerCore: token not supported");
_fees = _amount * flashLoanRate / 1e18;
}
/// @notice version of current Ruler Core hardcoded
function version() external pure override returns (string memory) {
return '1.0.3';
}
function _safeTransfer(IERC20 _token, address _account, uint256 _amount) private {
uint256 bal = _token.balanceOf(address(this));
if (bal < _amount) {
_token.safeTransfer(_account, bal);
} else {
_token.safeTransfer(_account, _amount);
}
}
function _sendAmtPostFeesOptionalAccrue(IERC20 _token, uint256 _amount, uint256 _feeRate, bool _accrue) private {
uint256 fees = _amount * _feeRate / 1e18;
_safeTransfer(_token, msg.sender, _amount - fees);
if (_accrue) {
feesMap[address(_token)] = feesMap[address(_token)] + fees;
}
}
function _createRToken(
address _col,
address _paired,
uint256 _expiry,
string calldata _expiryStr,
string calldata _mintRatioStr,
string memory _prefix
) private returns (address proxyAddr) {
uint8 decimals = uint8(IERC20(_paired).decimals());
require(decimals > 0, "RulerCore: paired decimals is 0");
string memory symbol = string(abi.encodePacked(
_prefix,
IERC20(_col).symbol(), "_",
_mintRatioStr, "_",
IERC20(_paired).symbol(), "_",
_expiryStr
));
bytes32 salt = keccak256(abi.encodePacked(_col, _paired, _expiry, _mintRatioStr, _prefix));
proxyAddr = Clones.cloneDeterministic(rERC20Impl, salt);
IRTokenProxy(proxyAddr).initialize("Ruler Protocol rToken", symbol, decimals);
emit RTokenCreated(proxyAddr);
}
function _getRTokenAmtFromColAmt(uint256 _colAmt, address _col, address _paired, uint256 _mintRatio) private view returns (uint256) {
uint8 colDecimals = IERC20(_col).decimals();
// pairedDecimals is the same as rToken decimals
uint8 pairedDecimals = IERC20(_paired).decimals();
return _colAmt * _mintRatio * (10 ** pairedDecimals) / (10 ** colDecimals) / 1e18;
}
function _getColAmtFromRTokenAmt(uint256 _rTokenAmt, address _col, address _rToken, uint256 _mintRatio) private view returns (uint256) {
uint8 colDecimals = IERC20(_col).decimals();
// pairedDecimals == rToken decimals
uint8 rTokenDecimals = IERC20(_rToken).decimals();
return _rTokenAmt * (10 ** colDecimals) * 1e18 / _mintRatio / (10 ** rTokenDecimals);
}
function _permit(address _token, Permit calldata permit) private {
IERC20Permit(_token).permit(
permit.owner,
permit.spender,
permit.amount,
permit.deadline,
permit.v,
permit.r,
permit.s
);
}
function _validateDepositInputs(address _col, Pair memory _pair) private view {
require(_pair.mintRatio != 0, "Ruler: pair does not exist");
require(_pair.active, "Ruler: pair inactive");
require(_pair.expiry - depositPauseWindow > block.timestamp, "Ruler: deposit ended");
// Oracle price is not required, the consequence is low since it will just allow users to deposit collateral (which can be collected thro repay before expiry. If default, early repayments will be diluted
if (address(oracle) != address(0)) {
uint256 colPrice = oracle.getPriceUSD(_col);
if (colPrice != 0) {
uint256 pairedPrice = oracle.getPriceUSD(_pair.pairedToken);
if (pairedPrice != 0) {
// colPrice / mintRatio (1e18) / pairedPrice > min collateralization ratio (1e18), if yes, revert deposit
require(colPrice * 1e36 > minColRatioMap[_col] * _pair.mintRatio * pairedPrice, "Ruler: collateral price too low");
}
}
}
}
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
/**
* @title Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
interface IERC3156FlashBorrower {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "./IERC3156FlashBorrower.sol";
interface IERC3156FlashLender {
/**
* @dev The amount of currency available to be lent.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(
address token
) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(
address token,
uint256 amount
) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "../ERC20/IERC20.sol";
/**
* @title RERC20 contract interface, implements {IERC20}. See {RERC20}.
* @author crypto-pumpkin
*/
interface IRERC20 is IERC20 {
/// @notice access restriction - owner (R)
function mint(address _account, uint256 _amount) external returns (bool);
function burnByRuler(address _account, uint256 _amount) external returns (bool);
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
/**
* @title Interface of the RTokens Proxy.
*/
interface IRTokenProxy {
function initialize(string calldata _name, string calldata _symbol, uint8 _decimals) external;
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "./IRERC20.sol";
import "./IOracle.sol";
/**
* @title IRulerCore contract interface. See {RulerCore}.
* @author crypto-pumpkin
*/
interface IRulerCore {
event RTokenCreated(address);
event CollateralUpdated(address col, uint256 old, uint256 _new);
event PairAdded(address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio);
event MarketMakeDeposit(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount);
event Deposit(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount);
event Repay(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount);
event Redeem(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount);
event Collect(address indexed user, address indexed collateral, address indexed paired, uint48 expiry, uint256 mintRatio, uint256 amount);
event AddressUpdated(string _type, address old, address _new);
event PausedStatusUpdated(bool old, bool _new);
event RERC20ImplUpdated(address rERC20Impl, address newImpl);
event FlashLoanRateUpdated(uint256 old, uint256 _new);
// v1.0.1
event FlashLoan(address _token, address _borrower, uint256 _amount);
// v1.0.2
event DepositPauseWindow(uint256 old, uint256 _new);
event RedeemFeeRateUpdated(uint256 old, uint256 _new);
struct Pair {
bool active;
uint48 expiry;
address pairedToken;
IRERC20 rcToken; // ruler capitol token, e.g. RC_Dai_wBTC_2_2021
IRERC20 rrToken; // ruler repayment token, e.g. RR_Dai_wBTC_2_2021
uint256 mintRatio; // 1e18, price of collateral / collateralization ratio
uint256 feeRate; // 1e18
uint256 colTotal;
}
struct Permit {
address owner;
address spender;
uint256 amount;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
// state vars
function oracle() external view returns (IOracle);
function version() external pure returns (string memory);
function flashLoanRate() external view returns (uint256);
function paused() external view returns (bool);
function responder() external view returns (address);
function feeReceiver() external view returns (address);
function rERC20Impl() external view returns (address);
function collaterals(uint256 _index) external view returns (address);
function minColRatioMap(address _col) external view returns (uint256);
function feesMap(address _token) external view returns (uint256);
function pairs(address _col, address _paired, uint48 _expiry, uint256 _mintRatio) external view returns (
bool active,
uint48 expiry,
address pairedToken,
IRERC20 rcToken,
IRERC20 rrToken,
uint256 mintRatio,
uint256 feeRate,
uint256 colTotal
);
function depositPauseWindow() external view returns (uint256);
function redeemFeeRate() external view returns (uint256);
// extra view
function getCollaterals() external view returns (address[] memory);
function getPairList(address _col) external view returns (Pair[] memory);
function viewCollectible(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) external view returns (uint256 colAmtToCollect, uint256 pairedAmtToCollect);
// user action - only when not paused
function mmDeposit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) external;
function mmDepositWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt,
Permit calldata _pairedPermit
) external;
function deposit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _colAmt
) external;
function depositWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _colAmt,
Permit calldata _colPermit
) external;
function redeem(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rTokenAmt
) external;
function repay(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rrTokenAmt
) external;
function repayWithPermit(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rrTokenAmt,
Permit calldata _pairedPermit
) external;
function collect(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
uint256 _rcTokenAmt
) external;
// access restriction - owner (dev)
function collectFees(IERC20[] calldata _tokens) external;
// access restriction - owner (dev) & responder
function setPaused(bool _paused) external;
// access restriction - owner (dev)
function addPair(
address _col,
address _paired,
uint48 _expiry,
string calldata _expiryStr,
uint256 _mintRatio,
string calldata _mintRatioStr,
uint256 _feeRate
) external;
function setPairActive(
address _col,
address _paired,
uint48 _expiry,
uint256 _mintRatio,
bool _active
) external;
function updateCollateral(address _col, uint256 _minColRatio) external;
function setFeeReceiver(address _addr) external;
function setResponder(address _addr) external;
function setRERC20Impl(address _addr) external;
function setOracle(address _addr) external;
function setFlashLoanRate(uint256 _newRate) external;
function setDepositPauseWindow(uint256 _newWindow) external;
function setRedeemFeeRate(uint256 _newFeeRate) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IOracle {
function getPriceUSD(address _asset) external view returns (uint256 price);
function getPricesUSD(address[] calldata _assets) external view returns (uint256[] memory prices);
// admin functions
function updateFeedETH(address _asset, address _feed) external;
function updateFeedUSD(address _asset, address _feed) external;
function setSushiKeeperOracle(address _sushiOracle) external;
function setUniKeeperOracle(address _uniOracle) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address payable) {
address payable addr;
require(address(this).balance >= amount, "Create2: insufficient balance");
require(bytecode.length != 0, "Create2: bytecode length is zero");
// solhint-disable-next-line no-inline-assembly
assembly {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
}
require(addr != address(0), "Create2: Failed on deploy");
return addr;
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) {
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)
);
return address(uint160(uint256(_data)));
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "./Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
* @author crypto-pumpkin
*
* By initialization, the owner account will be the one that called initializeOwner. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Ruler: Initializes the contract setting the deployer as the initial owner.
*/
function initializeOwner() internal initializer {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public 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.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;
function initializeReentrancyGuard () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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);
}
}
}
}
|
Returns the address where a contract will be stored if deployed via {deploy} from a contract located at `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}./
|
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) {
bytes32 _data = keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)
);
return address(uint160(uint256(_data)));
}
| 509,781
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Splitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*/
contract Splitter is Ownable {
uint256 private _relayerShare;
uint256 private _totalShares;
mapping(address => uint256) private _shares;
address payable[] private _payees;
event PayeeAdded(address account, uint256 shares);
event PayeeUpdated(uint256 payeeId, address payable oldPayee, uint256 oldShares, address payable newPayee, uint256 newShares);
event PayeeRemoved(uint256 payeeId, address payable payee, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
/**
* @dev Creates an instance of `Splitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(uint256 relayerShare_, address payable[] memory payees_, uint256[] memory shares_) payable {
require(payees_.length > 0, "Splitter: no payees");
require(payees_.length == shares_.length, "Splitter: payees and shares length mismatch");
_relayerShare = relayerShare_;
_totalShares = _totalShares + relayerShare_;
for (uint256 i = 0; i < payees_.length; i++) {
addPayee(payees_[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events.
* @param relayer The address of the relayer.
*/
function forward(address payable relayer) external payable {
_releaseInternal(relayer, _relayerShare);
for (uint256 i = 0; i < _payees.length; i++) {
_release(_payees[i]);
}
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the relayer share.
*/
function relayerShare() public view returns (uint256) {
return _relayerShare;
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Getter the payee array.
*/
function payees() public view returns (address payable[] memory) {
return _payees;
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function _release(address payable account) internal {
_releaseInternal(account, _shares[account]);
}
function _releaseInternal(address payable account, uint256 share) internal {
uint256 payment = (msg.value * share) / _totalShares;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract (for only owner).
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function addPayee(address payable account, uint256 shares_) public onlyOwner {
require(account != address(0), "PaymentSplitter: account is the zero address");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
/**
* @dev Update a payee to the contract (for only owner).
* @param payeeId The payee Id in array of the payee to update.
* @param newPayee The address of the payee to update.
* @param newShares_ The number of shares owned by the payee.
*/
function updatePayee(uint256 payeeId, address payable newPayee, uint256 newShares_) public onlyOwner {
require(newPayee != address(0), "PaymentSplitter: newPayee is the zero address");
require(payeeId < _payees.length, "PaymentSplitter: payeeId is more than payees length");
address payable oldPayee = _payees[payeeId];
_payees[payeeId] = newPayee;
uint256 oldShares = _shares[oldPayee];
_totalShares = _totalShares - oldShares + newShares_;
_shares[newPayee] = newShares_;
emit PayeeUpdated(payeeId, oldPayee, oldShares, newPayee, newShares_);
}
/**
* @dev Remove a payee to the contract (for only owner).
* @param payeeId The payee Id in array of the payee to remove.
*/
function removePayee(uint256 payeeId) public onlyOwner {
require(payeeId < _payees.length, "PaymentSplitter: payeeId is more than payees length");
uint lastId = _payees.length - 1;
address payable lastPayee = _payees[payeeId];
uint256 lastShares = _shares[lastPayee];
_payees.pop();
_totalShares = _totalShares - lastShares;
emit PayeeRemoved(lastId, lastPayee, lastShares);
if (lastId != payeeId) {
updatePayee(payeeId, lastPayee, lastShares);
}
}
}
|
Update a payee to the contract (for only owner). payeeId The payee Id in array of the payee to update. newPayee The address of the payee to update. newShares_ The number of shares owned by the payee./
|
function updatePayee(uint256 payeeId, address payable newPayee, uint256 newShares_) public onlyOwner {
require(newPayee != address(0), "PaymentSplitter: newPayee is the zero address");
require(payeeId < _payees.length, "PaymentSplitter: payeeId is more than payees length");
address payable oldPayee = _payees[payeeId];
_payees[payeeId] = newPayee;
uint256 oldShares = _shares[oldPayee];
_totalShares = _totalShares - oldShares + newShares_;
_shares[newPayee] = newShares_;
emit PayeeUpdated(payeeId, oldPayee, oldShares, newPayee, newShares_);
}
| 12,711,354
|
/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import './libraries/Operable.sol';
// import "@nomiclabs/buidler/console.sol";
// SousSummoner is the summoner of new tokens. She can summon any soul and she is a fair lady as well as a MasterChef.
contract SousSummoner is Ownable, Operable {
// Info of each user.
struct UserInfo {
uint256 amount; // How many SEANCE tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardPending;
//
// We do some fancy math here. Basically, any point in time, the amount of SEANCE
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt + user.rewardPending
//
// Whenever a user deposits or withdraws SEANCE tokens to a pool. Here's what happens:
// 1. The pool's `accRewardPerShare` (and `lastRewardTime`) gets updated.
// 2. User receives the pending reward sent to their address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of Pool
struct PoolInfo {
uint256 lastRewardTime; // Final timestamp (second) that Rewards distribution occurs.
uint256 accRewardPerShare; // Accumulated reward per share, times 1e12. See below.
}
// The SEANCE TOKEN!
IERC20 public seance;
// chains containing soussummoner
uint32 public chains = 1;
// rewards [[ / day ]].
uint256 public dailyReward = 250000;
// rewards [[ / second ]].
uint256 public rewardPerSecond = dailyReward / 86400;
// [[ pool ]] info.
PoolInfo public poolInfo;
// Info of each user that stakes Seance tokens.
mapping (address => UserInfo) public userInfo;
// addresses list
address[] public addressList;
// The timestamp (unix second) when mining starts.
uint256 public startTime = block.timestamp;
// The timestamp when mining ends.
uint256 public bonusEndTime = block.timestamp + 3650 days;
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
constructor(
IERC20 _seance
) {
seance = _seance;
// staking pool
poolInfo = PoolInfo({
lastRewardTime: startTime,
accRewardPerShare: 0
});
}
function addressLength() external view returns (uint256) {
return addressList.length;
}
// Return reward multiplier over the given _from to _to timestamp.
function getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) {
if (_to <= bonusEndTime) {
return _to - _from;
} else if (_from >= bonusEndTime) {
return 0;
} else {
return bonusEndTime - _from;
}
}
function updateRewards() internal {
dailyReward = dailyReward / chains;
rewardPerSecond = dailyReward / 86400;
}
function updateChains(uint32 _chains) public onlyOperator {
chains = _chains;
updateRewards();
}
// View function to see pending Tokens on frontend.
function pendingReward(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 stakedSupply = seance.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && stakedSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
uint256 tokenReward = multiplier * (rewardPerSecond / chains); // div(chains)
accRewardPerShare = accRewardPerShare + (tokenReward * 1e12 / stakedSupply);
}
return (user.amount * accRewardPerShare / 1e12) - (user.rewardDebt) + (user.rewardPending);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool() public {
if (block.timestamp <= poolInfo.lastRewardTime) {
return;
}
uint256 seanceSupply = seance.balanceOf(address(this));
if (seanceSupply == 0) {
poolInfo.lastRewardTime = block.timestamp;
return;
}
uint256 multiplier = getMultiplier(poolInfo.lastRewardTime, block.timestamp);
uint256 tokenReward = multiplier * rewardPerSecond / chains; // div(chains)
poolInfo.accRewardPerShare = poolInfo.accRewardPerShare + (tokenReward * 1e12 / seanceSupply);
poolInfo.lastRewardTime = block.timestamp;
}
// Deposit Seance tokens to SousSummoner for Reward allocation.
function deposit(uint256 _amount) public {
require (_amount > 0, 'amount 0');
UserInfo storage user = userInfo[msg.sender];
updatePool();
seance.transferFrom(address(msg.sender), address(this), _amount);
// The deposit behavior before farming will result in duplicate addresses, and thus we will manually remove them when airdropping.
if (user.amount == 0 && user.rewardPending == 0 && user.rewardDebt == 0) {
addressList.push(address(msg.sender));
}
user.rewardPending = (user.amount * poolInfo.accRewardPerShare / 1e12) - (user.rewardDebt + user.rewardPending);
user.amount = user.amount + _amount;
user.rewardDebt = user.amount * poolInfo.accRewardPerShare / 1e12;
emit Deposit(msg.sender, _amount);
}
// Withdraw Seance tokens from SousSummoner.
function withdraw(uint256 _amount) public {
require (_amount > 0, 'amount 0');
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "withdraw: overdraft amount, please select less.");
updatePool();
seance.transfer(address(msg.sender), _amount);
user.rewardPending = user.amount * poolInfo.accRewardPerShare / 1e12 - (user.rewardDebt + user.rewardPending);
user.amount = user.amount - _amount;
user.rewardDebt = user.amount * poolInfo.accRewardPerShare / 1e12;
emit Withdraw(msg.sender, _amount);
}
}
|
View function to see pending Tokens on frontend.
|
function pendingReward(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 stakedSupply = seance.balanceOf(address(this));
if (block.timestamp > pool.lastRewardTime && stakedSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardTime, block.timestamp);
accRewardPerShare = accRewardPerShare + (tokenReward * 1e12 / stakedSupply);
}
return (user.amount * accRewardPerShare / 1e12) - (user.rewardDebt) + (user.rewardPending);
}
| 12,906,808
|
./partial_match/1/0x6efA260a268e4AfAcf7fb91A6BF5f5B37379BF61/sources/BasketManager.sol
|
Removes a specific Asset from the Basket, given that its target/collateral level is already 0, throws if invalid. _assetToRemove The asset to remove from the basket/
|
function removeBasset(address _assetToRemove)
external
whenBasketIsHealthy
whenNotRecolling
managerOrGovernor
{
_removeBasset(_assetToRemove);
}
| 4,466,150
|
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* 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);
/**
* 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);
/**
* 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);
/**
* Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function decimals() external view returns (uint8);
/**
* 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);
/**
* 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;
/**
* 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 {
/**
* 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;
}
/**
* 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");
}
/**
* 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;
}
/**
* 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;
}
/**
* 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");
}
/**
* 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;
}
/**
* 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");
}
/**
* 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;
/**
* Collection of functions related to the address type
*/
library Address {
/**
* 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);
}
/**
* 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");
}
/**
* 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");
}
/**
* 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);
}
/**
* 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");
}
/**
* 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/ERC20.sol
pragma solidity ^0.6.0;
/**
* Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* 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;
}
/**
* Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* 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 override returns (uint8) {
return _decimals;
}
/**
* See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* 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;
}
/**
* See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** 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");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* 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");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* 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);
}
/**
* 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_;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* 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);
/**
* Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _owner;
}
/**
* Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/zs-XUSD2.sol
// zsTokens are Stabilize proxy tokens that serve as receipts for deposits into Stabilize strategies
// zsTokens should increase in value if the strategy it uses is profitable
// When someone deposits into the zsToken contract, tokens are minted and when they redeem, tokens are burned
interface StabilizeStrategy {
function rewardTokensCount() external view returns (uint256);
function rewardTokenAddress(uint256) external view returns (address);
function withdrawTokenReserves() external view returns (address, uint256);
function balance() external view returns (uint256);
function pricePerToken() external view returns (uint256);
function enter() external;
function exit() external;
function deposit(bool) external;
function withdraw(address, uint256, uint256, bool) external returns (uint256); // Will withdraw to the address specified a percent of total shares
}
pragma solidity =0.6.6;
contract zsToken is ERC20("Stabilize Strategy Emerging USD Tokens v2", "zs-XUSD2"), Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
// Variables
uint256 constant DIVISION_FACTOR = 100000;
// There are no fees to deposit and withdraw from the zs-Tokens
// Info of each user.
struct UserInfo {
uint256 depositTime; // The time the user made the last deposit
uint256 shareEstimate;
}
mapping(address => UserInfo) private userInfo;
// Token information
// This wrapped token accepts multiple stables
// USDN, MUSD, DUSD, USDP, ALUSD
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
address private _underlyingPriceAsset; // Token from which the price is derived for STBZ staking
bool public depositsOpen = true; // Governance can open or close deposits without timelock, cannot block withdrawals
// Strategy information
StabilizeStrategy private currentStrategy; // This will be the contract for the strategy
address private _pendingStrategy;
// Events
event Wrapped(address indexed user, uint256 amount);
event Unwrapped(address indexed user, uint256 amount);
constructor (address _priceAsset) public {
_underlyingPriceAsset = _priceAsset;
setupWithdrawTokens();
}
function setupWithdrawTokens() internal {
// USDN, MUSD, DUSD, UDSP, ALUSD
// Start with USDN (by Neutrino)
IERC20 _token = IERC20(address(0x674C6Ad92Fd080e4004b2312b45f796a192D27a0));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
// MUSD from MStable
_token = IERC20(address(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
// DUSD by DefiDollar
_token = IERC20(address(0x5BC25f649fc4e26069dDF4cF4010F9f706c23831));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
// USDP by Unit
_token = IERC20(address(0x1456688345527bE1f37E9e627DA0837D6f08C925));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
// ALUSD by Alchemix
_token = IERC20(address(0xBC6DA0FE9aD5f3b0d58160288917AA56653660E9));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
}
function getCurrentStrategy() external view returns (address) {
return address(currentStrategy);
}
function getPendingStrategy() external view returns (address) {
return _pendingStrategy;
}
function underlyingAsset() public view returns (address) {
// Can be used if staking in the STBZ pool
return address(_underlyingPriceAsset);
}
function underlyingDepositAssets() public view returns (address[] memory) {
// Returns all addresses accepted by this token vault
address[] memory addresses = new address[](tokenList.length);
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
addresses[i] = address(tokenList[i].token);
}
return addresses;
}
function pricePerToken() public view returns (uint256) {
if(totalSupply() == 0){
return 1e18; // Shown in Wei units
}else{
return uint256(1e18).mul(valueOfVaultAndStrategy()).div(totalSupply());
}
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
uint256 _balance = 0;
for(uint256 i = 0; i < tokenList.length; i++){
uint256 _bal = tokenList[i].token.balanceOf(_address);
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function valueOfVaultAndStrategy() public view returns (uint256) { // The total value of the tokens
uint256 balance = getNormalizedTotalBalance(address(this)); // Get tokens stored in this contract
if(currentStrategy != StabilizeStrategy(address(0))){
balance += currentStrategy.balance(); // And tokens stored at the strategy
}
return balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
// This function will return the address and amount of the token with the highest balance
if(currentStrategy != StabilizeStrategy(address(0))){
return currentStrategy.withdrawTokenReserves();
}else{
uint256 length = tokenList.length;
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normBal > 0){
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i;
}
}
}
if(targetNormBalance > 0){
return (address(tokenList[targetID].token), tokenList[targetID].token.balanceOf(address(this)));
}else{
return (address(0), 0); // No balance
}
}
}
// Now handle deposits into the strategy
function deposit(uint256 amount, uint256 _tokenID) public nonReentrant {
uint256 total = valueOfVaultAndStrategy(); // Get token equivalent at strategy and here if applicable
require(depositsOpen == true, "Deposits have been suspended, but you can still withdraw");
require(currentStrategy != StabilizeStrategy(address(0)),"No strategy contract has been selected yet");
require(_tokenID < tokenList.length, "Token ID is outside range of tokens in contract");
IERC20 _token = tokenList[_tokenID].token; // Trusted tokens
uint256 _before = _token.balanceOf(address(this));
_token.safeTransferFrom(_msgSender(), address(this), amount); // Transfer token to this address
amount = _token.balanceOf(address(this)).sub(_before); // Some tokens lose amount (transfer fee) upon transfer
require(amount > 0, "Cannot deposit 0");
bool nonContract = false;
if(tx.origin == _msgSender()){
nonContract = true; // The sender is not a contract
}
uint256 _strategyBalance = currentStrategy.balance(); // Will get the balance of the value of the main tokens at the strategy
// Now call the strategy to deposit
pushTokensToStrategy(); // Push any strategy tokens here into the strategy
currentStrategy.deposit(nonContract); // Activate strategy deposit
require(currentStrategy.balance() > _strategyBalance, "No change in strategy balance"); // Balance should increase
uint256 normalizedAmount = amount.mul(1e18).div(10**tokenList[_tokenID].decimals); // Make sure everything is same units
uint256 mintAmount = normalizedAmount;
if(totalSupply() > 0){
// There is already a balance here, calculate our share
mintAmount = normalizedAmount.mul(totalSupply()).div(total); // Our share of the total
}
_mint(_msgSender(),mintAmount); // Now mint new zs-token to the depositor
// Add the user information
userInfo[_msgSender()].depositTime = now;
userInfo[_msgSender()].shareEstimate = userInfo[_msgSender()].shareEstimate.add(mintAmount);
emit Wrapped(_msgSender(), amount);
}
function redeem(uint256 share) public nonReentrant {
// Essentially withdraw our equivalent share of the pool based on share value
// Users cannot choose which token they get. They get the largest quantity coin up to the lowest quantity
require(share > 0, "Cannot withdraw 0");
require(totalSupply() > 0, "No value redeemable");
uint256 tokenTotal = totalSupply();
// Now burn the token
_burn(_msgSender(),share); // Burn the amount, will fail if user doesn't have enough
bool nonContract = false;
if(tx.origin == _msgSender()){
nonContract = true; // The sender is not a contract, we will allow market sells and buys
}else{
// This is a contract redeeming
require(userInfo[_msgSender()].depositTime < now && userInfo[_msgSender()].depositTime > 0, "Contract depositor cannot redeem in same transaction");
}
// Update user information
if(share <= userInfo[_msgSender()].shareEstimate){
userInfo[_msgSender()].shareEstimate = userInfo[_msgSender()].shareEstimate.sub(share);
}else{
// Share is greater than our share estimate, can happen if tokens are transferred
userInfo[_msgSender()].shareEstimate = 0;
require(nonContract == true, "Contract depositors cannot take out more than what they put in");
}
uint256 withdrawAmount = 0;
if(currentStrategy != StabilizeStrategy(address(0))){
withdrawAmount = currentStrategy.withdraw(_msgSender(), share, tokenTotal, nonContract); // Returns the amount of underlying removed
require(withdrawAmount > 0, "Failed to withdraw from the strategy");
}else{
// Pull directly from this contract the token amount in relation to the share if strategy not used
if(share < tokenTotal){
uint256 _balance = getNormalizedTotalBalance(address(this));
uint256 _myBalance = _balance.mul(share).div(tokenTotal);
withdrawPerBalance(_msgSender(), _myBalance, false); // This will withdraw based on token balanace
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
uint256 _balance = getNormalizedTotalBalance(address(this));
withdrawPerBalance(_msgSender(), _balance, true);
withdrawAmount = _balance;
}
}
emit Unwrapped(_msgSender(), withdrawAmount);
}
// This will withdraw the tokens from the contract based on their balance, from highest balance to lowest
function withdrawPerBalance(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
if(_takeAll == true){
// Send the entire balance
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
tokenList[i].token.safeTransfer(_receiver, _bal);
}
}
return;
}
bool[] memory done = new bool[](length);
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
targetNormBalance = 0; // Reset the target balance
// Find the highest balanced token to withdraw
for(uint256 i2 = 0; i2 < length; i2++){
if(done[i2] == false){
uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals);
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i2;
}
}
}
done[targetID] = true;
// Determine the balance left
uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].token.balanceOf(address(this)));
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
uint256 _balance = _withdrawAmount.mul(10**tokenList[targetID].decimals).div(1e18);
_withdrawAmount = 0;
tokenList[targetID].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
// Governance functions
// Stop/start all deposits, no timelock required
// --------------------
function stopDeposits() external onlyGovernance {
depositsOpen = false;
}
function startDeposits() external onlyGovernance {
depositsOpen = true;
}
// A function used in case of strategy failure, possibly due to bug in the platform our strategy is using, governance can stop using it quick
function emergencyStopStrategy() external onlyGovernance {
depositsOpen = false;
if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
currentStrategy.exit(); // Pulls all the tokens and accessory tokens from the strategy
}
currentStrategy = StabilizeStrategy(address(0));
_timelockType = 0; // Prevent governance from changing to new strategy without timelock
}
// --------------------
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(totalSupply() > 0){
// Timelock is only required after tokens exist
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeStrategy(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
_pendingStrategy = _address;
if(totalSupply() == 0){
// Can change strategy with one call in this case
finishChangeStrategy();
}
}
function finishChangeStrategy() public onlyGovernance timelockConditionsMet(2) {
if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
currentStrategy.exit(); // Pulls all the tokens and accessory tokens from the strategy
}
currentStrategy = StabilizeStrategy(_timelock_address);
if(currentStrategy != StabilizeStrategy(address(0)) && totalSupply() > 0){
pushTokensToStrategy(); // It will push any strategy reward tokens here to the new strategy
currentStrategy.enter(); // Puts all the tokens and accessory tokens into the new strategy
}
_pendingStrategy = address(0);
}
function pushTokensToStrategy() internal {
uint256 tokenCount = currentStrategy.rewardTokensCount();
for(uint256 i = 0; i < tokenCount; i++){
IERC20 _token = IERC20(address(currentStrategy.rewardTokenAddress(i)));
uint256 _balance = _token.balanceOf(address(this));
if(_balance > 0){
_token.safeTransfer(address(currentStrategy), _balance);
}
}
}
// --------------------
// Add a new token to the strategy
// --------------------
function startAddNewStableToken(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishAddNewStableToken() public onlyGovernance timelockConditionsMet(3) {
IERC20 _token = IERC20(address(_timelock_address));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
}
}
|
Returns all addresses accepted by this token vault
|
function underlyingDepositAssets() public view returns (address[] memory) {
address[] memory addresses = new address[](tokenList.length);
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
addresses[i] = address(tokenList[i].token);
}
return addresses;
}
| 481,487
|
pragma solidity >=0.4.24;
import "openzeppelin-solidity/contracts/utils/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* CONSTANTS */
/********************************************************************************************/
// define the amount an airline must fund before it can participate in the contract
uint256 private constant AIRLINE_MINUMIM_FUNDING = 10 ether;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping(address => uint256) private authorizedContracts;
/********************************************************************************************/
/* DATA STRUCTURES */
/********************************************************************************************/
// Airlines
struct Airline {
bool isRegistered;
string name;
uint updatedTimestamp;
uint256 funding;
uint256 registrationVotes;
mapping(address => bool) voters;
}
mapping(address => Airline) private airlines;
uint256 private registeredAirlines = 0;
// Flights
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
uint256 private registeredFlights = 0;
// Insurance
struct Insurance {
address airline;
bytes32 flightCode;
uint256 insurance;
address passenger;
uint256 credit;
}
// Tracks a passengers set of insurances
mapping(address => Insurance[]) private insurancePoliciesPassenger;
// Tracks a airline set of insurances
mapping(address => Insurance[]) private insurancePoliciesAirlines;
uint256 private registeredInsurance = 0;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event InsuranceCredited(address passenger, uint256 credit);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor()
{
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");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires an authorized contract to be the function caller
*/
modifier requireAuthorizedContract()
{
require(authorizedContracts[msg.sender] == 1, "Caller is not authorized contract");
_;
}
/**
* @dev Modifier that requires there to be no airlines registered
*
*/
modifier requireZeroRegisteredAirlines()
{
require(numRegisteredAirlines() == 0, "There are > 0 airlines registered already");
_;
}
/**
* @dev Modifier that requires a voting airline has not yet voted
*
*/
modifier requireVoterNotVoted(address airline, address voter)
{
require(airlines[airline].voters[voter] == false, "Airline has already voted");
_;
}
modifier requireFlightRegistered(bytes32 flightCode)
{
require(flights[flightCode].isRegistered == true, "Flight is not registered");
_;
}
/********************************************************************************************/
/* 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 Determine if the specified address is that of a registered airline
*
* @return A bool that indicates if the address is an airline
*/
function isAirline(address a) public
view
returns(bool)
{
if ((airlines[a].isRegistered == true) &&
(bytes(airlines[a].name).length != 0))
{
return true;
}
else
{
return false;
}
}
/**
* @dev Determine if the specified airline is funded
*
* @return A bool that indicates if the airline is funded
*/
function isAirlineFunded(address a) public
view
returns(bool)
{
return airlines[a].funding >= AIRLINE_MINUMIM_FUNDING;
}
/**
* @dev Determine the specified airlines name
*
* @return string
*/
function airlineName(address a) public
view
returns(string memory)
{
return airlines[a].name;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) external
requireContractOwner()
{
operational = mode;
}
function authorizeContract(address contractAddress) external
requireContractOwner()
{
authorizedContracts[contractAddress] = 1;
}
function deauthorizeContract(address contractAddress) external
requireContractOwner()
{
delete authorizedContracts[contractAddress];
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add the first airline
* Can only be called from FlightSuretyApp contract
*
*/
function registerFirstAirline(address firstAirline, string memory firstAirlineName) external
requireAuthorizedContract()
requireZeroRegisteredAirlines()
returns (bool success)
{
Airline storage a = airlines[firstAirline];
a.isRegistered = true;
a.name = firstAirlineName;
a.updatedTimestamp = block.timestamp;
a.funding = 0 ether;
a.registrationVotes = 0;
registeredAirlines++;
return true;
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address newAirline, string memory name) external
requireAuthorizedContract()
returns (bool success)
{
Airline storage a = airlines[newAirline];
a.isRegistered = true;
a.name = name;
a.updatedTimestamp = block.timestamp;
a.funding = 0 ether;
a.registrationVotes = 0;
registeredAirlines++;
return true;
}
/**
* @dev Fund an airline - which is required before it participate in contract
*
*/
function fundAirline(address payable airline, uint256 value) external
payable
{
Airline storage a = airlines[airline];
a.funding += value;
}
/**
* @dev Fund an airline - which is required before it participate in contract
*
*/
function airlineFunding(address airline) external
view
returns (uint256)
{
Airline storage a = airlines[airline];
return a.funding;
}
/**
* @dev Return the number of registered airlines
*
*/
function numRegisteredAirlines() public
view
returns(uint256)
{
return registeredAirlines;
}
/**
* @dev Register a vote to to support registration of an airline
*
* Only registered and funded airlines can vote in support of registering another airline
*/
function voteToRegisterAirline(address newAirline, address voter) external
requireAuthorizedContract()
requireVoterNotVoted(newAirline, voter)
{
Airline storage a = airlines[newAirline];
a.registrationVotes += 1;
a.voters[voter] = true;
}
/**
* @dev Return the number of votes supporting airline registration
*
*/
function votesSupportingAirlineRegistration(address newAirline) external
view
returns(uint256)
{
Airline storage a = airlines[newAirline];
return a.registrationVotes;
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerFlight(bytes32 flightCode, uint8 status, address airline) external
requireAuthorizedContract()
returns (bool success)
{
Flight storage f = flights[flightCode];
if (f.isRegistered == true)
{
// already registered
return false;
}
f.isRegistered = true;
f.statusCode = status;
f.airline = airline;
f.updatedTimestamp = block.timestamp;
registeredFlights++;
return true;
}
/**
* @dev Function to determine if the specified flight is
* registered agains the airline
*
*/
function isFlightRegistered(address airline, bytes32 flightCode) external
view
returns(bool)
{
Flight storage f = flights[flightCode];
return (f.airline == airline);
}
/**
* @dev Update the flight status of the indicated flight
*/
function updateFlightStatus(bytes32 flightCode, uint8 status, uint256 timestamp) external
requireAuthorizedContract()
requireFlightRegistered(flightCode)
returns(bool)
{
Flight storage f = flights[flightCode];
if (f.statusCode != status)
{
f.statusCode = status;
f.updatedTimestamp = timestamp;
return true;
}
return false;
}
/**
* @dev Get the flight status of the indicated flight
*/
function getFlightStatus(bytes32 flightCode) external
view
requireAuthorizedContract()
requireFlightRegistered(flightCode)
returns (uint8)
{
Flight storage f = flights[flightCode];
return f.statusCode;
}
/**
* @dev Get the airline that is running the indicated flight
*/
function getFlightAirline(bytes32 flightCode) external
view
requireAuthorizedContract()
requireFlightRegistered(flightCode)
returns (address)
{
Flight storage f = flights[flightCode];
return f.airline;
}
/**
* @dev Return the number of registered airlines
*
*/
function numRegisteredFlights() external
view
returns(uint256)
{
return registeredFlights;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(address airline, string memory airlineName, bytes32 flightCode,
address passenger, uint256 value) external
payable
requireAuthorizedContract()
requireFlightRegistered(flightCode)
{
Insurance[] storage ip = insurancePoliciesPassenger[passenger];
Insurance[] storage ia = insurancePoliciesAirlines[airline];
ip.push(Insurance(airline, flightCode, value, passenger, 0));
ia.push(Insurance(airline, flightCode, value, passenger, 0));
registeredInsurance += 1;
}
/**
* @dev Return the number of registered insurance policies on the contract
*
*/
function numRegisteredInsurancePolicies() external
view
returns(uint256)
{
return registeredInsurance;
}
/**
* @dev Return the number of registered insurance policies for a passenger
*
*/
function numRegisteredInsurancePoliciesForPassenger(address passenger) external
view
returns(uint256)
{
Insurance[] storage i = insurancePoliciesPassenger[passenger];
return i.length;
}
/**
* @dev Return the airline address of registered insurance policy for the indicated passenger
*
*/
function insurancePoliciesForPassengerAirline(address passenger, uint256 policyNumber) external
view
returns(address)
{
Insurance[] storage i = insurancePoliciesPassenger[passenger];
return i[policyNumber].airline;
}
/**
* @dev Return the flight name of registered insurance policy for the indicated passenger
*
*/
function insurancePoliciesForPassengerFlightName(address passenger, uint256 policyNumber) external
view
returns(bytes32)
{
Insurance[] storage i = insurancePoliciesPassenger[passenger];
return i[policyNumber].flightCode;
}
/**
* @dev Return the insured amount of registered insurance policy for the indicated passenger
*
*/
function insurancePoliciesForPassengerInsuranceAmount(address passenger, uint256 policyNumber) external
view
returns(uint256)
{
Insurance[] storage i = insurancePoliciesPassenger[passenger];
return i[policyNumber].insurance;
}
/**
* @dev Return the insured amount of registered insurance policy for the indicated passenger
*
*/
function insurancePoliciesForPassengerCreditAmount(address passenger, uint256 policyNumber) external
view
returns(uint256)
{
Insurance[] storage i = insurancePoliciesPassenger[passenger];
return i[policyNumber].credit;
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(address airline, bytes32 flightCode) external
{
Insurance[] storage ia = insurancePoliciesAirlines[airline];
for (uint i = 0; i < ia.length; i++) {
if (ia[i].flightCode == flightCode){
address passenger = ia[i].passenger;
uint256 insuredAmount = ia[i].insurance;
uint256 credit = insuredAmount.mul(15).div(10);
ia[i].credit += credit;
Insurance[] storage ip = insurancePoliciesPassenger[passenger];
for (uint j = 0; j < ip.length; j++) {
if (ip[j].airline == airline && ip[j].flightCode == flightCode){
ip[j].credit += credit;
emit InsuranceCredited(passenger, credit);
}
}
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(address passenger, address airline, bytes32 flightCode, uint256 amount) external
payable
{
Insurance[] storage ip = insurancePoliciesPassenger[passenger];
for (uint j = 0; j < ip.length; j++) {
if (ip[j].airline == airline && ip[j].flightCode == flightCode){
uint256 available_credit = ip[j].credit;
require(available_credit >= amount);
ip[j].credit -= amount;
}
}
Insurance[] storage ia = insurancePoliciesAirlines[airline];
for (uint i = 0; i < ia.length; i++) {
if (ia[i].flightCode == flightCode && ia[i].passenger == passenger){
ia[i].credit -= amount;
}
}
address payable passengerPay = payable(passenger);
passengerPay.transfer(amount);
}
/**
* @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 memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
receive() external payable
{
fund();
}
}
|
Transfers eligible payout funds to insuree/
|
function pay(address passenger, address airline, bytes32 flightCode, uint256 amount) external
payable
{
Insurance[] storage ip = insurancePoliciesPassenger[passenger];
for (uint j = 0; j < ip.length; j++) {
if (ip[j].airline == airline && ip[j].flightCode == flightCode){
uint256 available_credit = ip[j].credit;
require(available_credit >= amount);
ip[j].credit -= amount;
}
}
Insurance[] storage ia = insurancePoliciesAirlines[airline];
for (uint i = 0; i < ia.length; i++) {
if (ia[i].flightCode == flightCode && ia[i].passenger == passenger){
ia[i].credit -= amount;
}
}
address payable passengerPay = payable(passenger);
passengerPay.transfer(amount);
}
| 12,972,324
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.8;
import "../node_modules/openzeppelin-solidity/contracts/utils/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
struct airlineStruct {
bool isRegistered;
bool isOperational;
uint256 funds;
}
struct Passenger {
address wallet;
uint256 insuranceCredit;
uint256 amount;
bool isCredited;
}
struct Flight {
bool isRegistered;
string from;
string destination;
string flightCode;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
uint256 multiplier;
address[] passengersList;
}
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
uint256 private airLinesCount = 0; // counter of airlines
address private authorizeCallerAddress; // set the account authorized to call this contract
mapping(bytes32 => Flight) private flights; // set the list of flights
mapping(address => airlineStruct) airlines; //set the list of airlines
mapping(address => address[]) votesRegistration; // set the list of votes for the address
mapping(address => Passenger) private passengers; // set list of passengers
// mapping(address => Passenger[]) passengersInsurance;
// Flight status codeesregisterAirline
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event RegisterAirline(address account);
event FundingAirline(address account, uint256 value);
event FlightRegistered(bytes32 flightKey, address airline);
event FlightInsuranceBought(address account, string flightKey);
event InsureeCredited(address account, uint256 value);
event AccountWithdrawn(address account, uint256 value);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor() {
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");
_;
}
modifier requireCallerAuthorized() {
require(
msg.sender == authorizeCallerAddress,
"Caller is not authorized"
);
_;
}
/********************************************************************************************/
/* 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;
}
function setVoteAirline(address airline) public requireCallerAuthorized {
votesRegistration[airline].push(msg.sender);
}
function getAirlineRegistered(address airline)
public
view
requireCallerAuthorized
returns (bool)
{
return (airlines[airline].isRegistered);
}
function getAirlineOperational(address airline)
public
view
requireCallerAuthorized
returns (bool)
{
return (airlines[airline].isOperational);
}
function getAirlineFunds(address airline)
public
view
requireCallerAuthorized
returns (uint256)
{
return (airlines[airline].funds);
}
function authorizeCaller(address caller) public {
authorizeCallerAddress = caller;
}
function getAirlineVotes(address airline)
public
view
requireCallerAuthorized
returns (uint256)
{
return votesRegistration[airline].length;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address airline, bool isAirlineOperational)
external
{
// Register the airline as Registered, but is Operational unitl they submit 10 ether
airlines[airline] = airlineStruct({
isRegistered: true,
isOperational: isAirlineOperational,
funds: 0
});
airLinesCount = airLinesCount + 1;
emit RegisterAirline(airline);
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(
address passenger,
string memory flightCode,
uint256 value,
address airline,
uint256 timestamp
) external requireCallerAuthorized {
Flight storage flightData = flights[
keccak256(abi.encodePacked(airline, flightCode, timestamp))
];
flightData.passengersList.push(passenger);
Passenger storage flightPassengerInsurance = passengers[passenger];
flightPassengerInsurance.wallet = passenger;
flightPassengerInsurance.insuranceCredit = 0;
flightPassengerInsurance.amount = value;
flightPassengerInsurance.isCredited = false;
emit FlightInsuranceBought(passenger, flightCode);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(
string memory flightCode,
address airline,
uint256 timestamp
) internal requireIsOperational requireCallerAuthorized {
Flight storage flightData = flights[
keccak256(abi.encodePacked(airline, flightCode, timestamp))
];
for (uint256 i = 0; i < flightData.passengersList.length; i++) {
Passenger memory passenger = passengers[
flightData.passengersList[i]
];
if (passenger.isCredited == false) {
passenger.isCredited = true;
uint256 amount = passenger
.amount
.mul(flightData.multiplier)
.div(100);
passengers[flightData.passengersList[i]]
.insuranceCredit += amount;
emit InsureeCredited(passenger.wallet, amount);
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(address passenger)
external
requireIsOperational
requireCallerAuthorized
{
require(passenger == tx.origin, "Contracts not allowed");
require(
passengers[passenger].insuranceCredit > 0,
"No fund available for withdrawal"
);
uint256 amount = passengers[passenger].insuranceCredit;
passengers[passenger].insuranceCredit = 0;
passengers[passenger].amount = 0;
passengers[passenger].isCredited = false;
payable(passenger).transfer(amount);
emit AccountWithdrawn(passenger, amount);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fundAirline(address airline, uint256 amount) public {
airlines[airline].funds = airlines[airline].funds + amount;
if (airlines[airline].funds >= 10 ether) {
airlines[airline].isOperational = true;
}
emit FundingAirline(airline, amount);
}
function getFlightKey(
address airline,
string memory flight,
uint256 timestamp
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function getAirlinesLength() public view returns (uint256) {
return airLinesCount;
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight(
string memory destination,
string memory from,
string memory flight,
address airline,
uint256 timestamp,
uint256 multiplier
) external {
bytes32 key = getFlightKey(airline, flight, timestamp);
require(!flights[key].isRegistered, "Flight is already registered.");
require(
getAirlineOperational(airline) == true,
"Airline isn't operational."
);
Flight storage flightData = flights[key];
flightData.isRegistered = true;
flightData.flightCode = flight;
flightData.destination = destination;
flightData.from = from;
flightData.statusCode = STATUS_CODE_UNKNOWN;
flightData.updatedTimestamp = timestamp;
flightData.airline = airline;
flightData.multiplier = multiplier;
emit FlightRegistered(key, airline);
}
function isValidFlight(
string memory flightCode,
address airline,
uint256 timestamp
) external view requireCallerAuthorized returns (bool isValid) {
bytes32 key = keccak256(
abi.encodePacked(airline, flightCode, timestamp)
);
isValid = flights[key].isRegistered;
}
function processFlightStatus(
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
) external requireCallerAuthorized {
if (
(statusCode == STATUS_CODE_LATE_AIRLINE) ||
(statusCode == STATUS_CODE_LATE_TECHNICAL)
) {
creditInsurees(flight, airline, timestamp);
}
}
function isOnPassengerOnFlight(
address airline,
string memory flight,
uint256 timestamp,
address passenger
) external view returns (bool) {
bytes32 key = keccak256(abi.encodePacked(airline, flight, timestamp));
require(flights[key].isRegistered, "Flight is already registered.");
bool checker;
address[] storage passengerData = flights[key].passengersList;
for (uint256 i = 0; i < passengerData.length; i++) {
if (passengerData[i] == passenger) {
checker = true; //or whatever you want to do if it matches
}
}
return checker;
}
function getPassengerInsuranceCredit(address wallet)
external
view
returns (uint256)
{
return passengers[wallet].insuranceCredit;
}
/**
* @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 requireIsOperational {}
/**
* @dev Fallback function for funding smart contract.
*
*/
fallback() external payable {
fund();
}
receive() external payable {}
}
|
Credits payouts to insurees/
|
function creditInsurees(
string memory flightCode,
address airline,
uint256 timestamp
) internal requireIsOperational requireCallerAuthorized {
Flight storage flightData = flights[
keccak256(abi.encodePacked(airline, flightCode, timestamp))
];
for (uint256 i = 0; i < flightData.passengersList.length; i++) {
Passenger memory passenger = passengers[
flightData.passengersList[i]
];
if (passenger.isCredited == false) {
passenger.isCredited = true;
uint256 amount = passenger
.amount
.mul(flightData.multiplier)
.div(100);
passengers[flightData.passengersList[i]]
.insuranceCredit += amount;
emit InsureeCredited(passenger.wallet, amount);
}
}
}
| 5,370,349
|
pragma solidity 0.5.15;
pragma experimental ABIEncoderV2;
// YAM rebaser V2 - Uses sushiswap for rebase sales, purchases ETH, uses two hop oracle pricing
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev 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);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call.value(weiValue)(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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");
}
}
}
interface UniswapPair {
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;
}
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair,
bool isToken0
) internal view returns (uint priceCumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = UniswapPair(pair).getReserves();
if (isToken0) {
priceCumulative = UniswapPair(pair).price0CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
priceCumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
}
} else {
priceCumulative = UniswapPair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
priceCumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
}
// Storage for a YAM token
contract YAMTokenStorage {
using SafeMath for uint256;
/**
* @dev Guard variable for re-entrancy checks. Not currently used
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/**
* @notice Approved rebaser for this contract
*/
address public rebaser;
/**
* @notice Approved migrator for this contract
*/
address public migrator;
/**
* @notice Incentivizer address of YAM protocol
*/
address public incentivizer;
/**
* @notice Total supply of YAMs
*/
uint256 public totalSupply;
/**
* @notice Internal decimals used to handle scaling factor
*/
uint256 public constant internalDecimals = 10**24;
/**
* @notice Used for percentage maths
*/
uint256 public constant BASE = 10**18;
/**
* @notice Scaling factor that adjusts everyone's balances
*/
uint256 public yamsScalingFactor;
mapping (address => uint256) internal _yamBalances;
mapping (address => mapping (address => uint256)) internal _allowedFragments;
uint256 public initSupply;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
}
/* Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
contract YAMGovernanceStorage {
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
}
contract YAMTokenInterface is YAMTokenStorage, YAMGovernanceStorage {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Event emitted when tokens are rebased
*/
event Rebase(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor);
/*** Gov Events ***/
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
/**
* @notice Sets the rebaser contract
*/
event NewRebaser(address oldRebaser, address newRebaser);
/**
* @notice Sets the migrator contract
*/
event NewMigrator(address oldMigrator, address newMigrator);
/**
* @notice Sets the incentivizer contract
*/
event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
/* - ERC20 Events - */
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/* - Extra Events - */
/**
* @notice Tokens minted event
*/
event Mint(address to, uint256 amount);
// Public functions
function transfer(address to, uint256 value) external returns(bool);
function transferFrom(address from, address to, uint256 value) external returns(bool);
function balanceOf(address who) external view returns(uint256);
function balanceOfUnderlying(address who) external view returns(uint256);
function allowance(address owner_, address spender) external view returns(uint256);
function approve(address spender, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function maxScalingFactor() external view returns (uint256);
function yamToFragment(uint256 yam) external view returns (uint256);
function fragmentToYam(uint256 value) external view returns (uint256);
/* - Governance Functions - */
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegate(address delegatee) external;
function delegates(address delegator) external view returns (address);
function getCurrentVotes(address account) external view returns (uint256);
/* - Permissioned/Governance functions - */
function mint(address to, uint256 amount) external returns (bool);
function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
function _setRebaser(address rebaser_) external;
function _setIncentivizer(address incentivizer_) external;
function _setPendingGov(address pendingGov_) external;
function _acceptGov() external;
}
interface BAL {
function gulp(address token) external;
}
contract YAMRebaser2 {
using SafeMath for uint256;
modifier onlyGov() {
require(msg.sender == gov);
_;
}
struct Transaction {
bool enabled;
address destination;
bytes data;
}
struct UniVars {
uint256 yamsToUni;
uint256 amountFromReserves;
uint256 mintToReserves;
}
/// @notice an event emitted when a transaction fails
event TransactionFailed(address indexed destination, uint index, bytes data);
/// @notice an event emitted when maxSlippageFactor is changed
event NewMaxSlippageFactor(uint256 oldSlippageFactor, uint256 newSlippageFactor);
/// @notice an event emitted when deviationThreshold is changed
event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold);
/// @notice an event emitted during rebase denoting how much is minted
event MintAmount(uint256 mintAmount);
/**
* @notice Sets the treasury mint percentage of rebase
*/
event NewRebaseMintPercent(uint256 oldRebaseMintPerc, uint256 newRebaseMintPerc);
/**
* @notice Sets the reserve contract
*/
event NewReserveContract(address oldReserveContract, address newReserveContract);
/**
* @notice Sets the reserve contract
*/
event TreasuryIncreased(uint256 reservesAdded, uint256 yamsSold, uint256 yamsFromReserves, uint256 yamsToReserves);
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
// Stable ordering is not guaranteed.
Transaction[] public transactions;
/// @notice Governance address
address public gov;
/// @notice Pending Governance address
address public pendingGov;
/// @notice Spreads out getting to the target price
uint256 public rebaseLag;
/// @notice Peg target
uint256 public targetRate;
/// @notice Percent of rebase that goes to minting for treasury building
uint256 public rebaseMintPerc;
// If the current exchange rate is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the rate.
// (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change.
uint256 public deviationThreshold;
/// @notice More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec;
/// @notice Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
/// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec;
/// @notice The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec;
/// @notice The number of rebase cycles since inception
uint256 public epoch;
// rebasing is not active initially. It can be activated at T+12 hours from
// deployment time
///@notice boolean showing rebase activation status
bool public rebasingActive;
/// @notice delays rebasing activation to facilitate liquidity
uint256 public constant rebaseDelay = 12 hours;
/// @notice Time of TWAP initialization
uint256 public timeOfTWAPInit;
/// @notice YAM token address
address public yamAddress;
/// @notice reserve token
address public reserveToken;
/// @notice Reserves vault contract
address public reservesContract;
/// @notice pair for reserveToken <> YAM
address public trade_pair;
/// @notice pair for reserveToken <> YAM
address public eth_usdc_pair;
/// @notice list of uniswap pairs to sync
address[] public uniSyncPairs;
/// @notice list of balancer pairs to gulp
address[] public balGulpPairs;
/// @notice last TWAP update time
uint32 public blockTimestampLast;
/// @notice last TWAP cumulative price;
uint256 public priceCumulativeLastYAMETH;
/// @notice last TWAP cumulative price;
uint256 public priceCumulativeLastETHUSDC;
/// @notice address to send part of treasury to
address public public_goods;
/// @notice percentage of treasury to send to public goods address
uint256 public public_goods_perc;
// Max slippage factor when buying reserve token. Magic number based on
// the fact that uniswap is a constant product. Therefore,
// targeting a % max slippage can be achieved by using a single precomputed
// number. i.e. 2.5% slippage is always equal to some f(maxSlippageFactor, reserves)
/// @notice the maximum slippage factor when buying reserve token
uint256 public maxSlippageFactor;
/// @notice Whether or not this token is first in uniswap YAM<>Reserve pair
bool public isToken0;
uint256 public constant BASE = 10**18;
uint256 public constant MAX_SLIPPAGE_PARAM = 1180339 * 10**11; // max ~20% market impact
uint256 public constant MAX_MINT_PERC_PARAM = 25 * 10**16; // max 25% of rebase can go to treasury
constructor(
address yamAddress_,
address reserveToken_,
address factory,
address reservesContract_,
address public_goods_,
uint256 public_goods_perc_
)
public
{
minRebaseTimeIntervalSec = 12 hours;
rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases
(address token0, address token1) = sortTokens(yamAddress_, reserveToken_);
// used for interacting with uniswap
if (token0 == yamAddress_) {
isToken0 = true;
} else {
isToken0 = false;
}
// uniswap YAM<>Reserve pair
trade_pair = pairForSushi(factory, token0, token1);
// get eth_usdc piar
address USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
// USDC < WETH address, so USDC is token0
eth_usdc_pair = pairForSushi(factory, USDC, reserveToken_);
// Reserves contract is mutable
reservesContract = reservesContract_;
// Reserve token is not mutable. Must deploy a new rebaser to update it
reserveToken = reserveToken_;
yamAddress = yamAddress_;
public_goods = public_goods_;
public_goods_perc = public_goods_perc_;
// target 5% slippage
// ~2.6%
maxSlippageFactor = 2597836 * 10**10; //5409258 * 10**10;
// $1
targetRate = BASE;
// twice daily rebase, with targeting reaching peg in 10 days
rebaseLag = 20;
// 10%
rebaseMintPerc = 10**17;
// 5%
deviationThreshold = 5 * 10**16;
// 60 minutes
rebaseWindowLengthSec = 60 * 60;
// Changed in deployment scripts to facilitate protocol initiation
gov = msg.sender;
}
function removeUniPair(uint256 index) public onlyGov {
if (index >= uniSyncPairs.length) return;
for (uint i = index; i < uniSyncPairs.length-1; i++){
uniSyncPairs[i] = uniSyncPairs[i+1];
}
uniSyncPairs.length--;
}
function removeBalPair(uint256 index) public onlyGov {
if (index >= balGulpPairs.length) return;
for (uint i = index; i < balGulpPairs.length-1; i++){
balGulpPairs[i] = balGulpPairs[i+1];
}
balGulpPairs.length--;
}
/**
@notice Adds pairs to sync
*
*/
function addSyncPairs(address[] memory uniSyncPairs_, address[] memory balGulpPairs_)
public
onlyGov
{
for (uint256 i = 0; i < uniSyncPairs_.length; i++) {
uniSyncPairs.push(uniSyncPairs_[i]);
}
for (uint256 i = 0; i < balGulpPairs_.length; i++) {
balGulpPairs.push(balGulpPairs_[i]);
}
}
/**
@notice Uniswap synced pairs
*
*/
function getUniSyncPairs()
public
view
returns (address[] memory)
{
address[] memory pairs = uniSyncPairs;
return pairs;
}
/**
@notice Uniswap synced pairs
*
*/
function getBalGulpPairs()
public
view
returns (address[] memory)
{
address[] memory pairs = balGulpPairs;
return pairs;
}
/**
@notice Updates slippage factor
@param maxSlippageFactor_ the new slippage factor
*
*/
function setMaxSlippageFactor(uint256 maxSlippageFactor_)
public
onlyGov
{
require(maxSlippageFactor_ < MAX_SLIPPAGE_PARAM);
uint256 oldSlippageFactor = maxSlippageFactor;
maxSlippageFactor = maxSlippageFactor_;
emit NewMaxSlippageFactor(oldSlippageFactor, maxSlippageFactor_);
}
/**
@notice Updates rebase mint percentage
@param rebaseMintPerc_ the new rebase mint percentage
*
*/
function setRebaseMintPerc(uint256 rebaseMintPerc_)
public
onlyGov
{
require(rebaseMintPerc_ < MAX_MINT_PERC_PARAM);
uint256 oldPerc = rebaseMintPerc;
rebaseMintPerc = rebaseMintPerc_;
emit NewRebaseMintPercent(oldPerc, rebaseMintPerc_);
}
/**
@notice Updates reserve contract
@param reservesContract_ the new reserve contract
*
*/
function setReserveContract(address reservesContract_)
public
onlyGov
{
address oldReservesContract = reservesContract;
reservesContract = reservesContract_;
emit NewReserveContract(oldReservesContract, reservesContract_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/** @notice Initializes TWAP start point, starts countdown to first rebase
*
*/
function init_twap()
public
{
require(timeOfTWAPInit == 0, "already activated");
(uint priceCumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(trade_pair, isToken0);
(uint priceCumulativeUSDC, ) =
UniswapV2OracleLibrary.currentCumulativePrices(eth_usdc_pair, false);
require(blockTimestamp > 0, "no trades");
blockTimestampLast = blockTimestamp;
priceCumulativeLastYAMETH = priceCumulative;
priceCumulativeLastETHUSDC = priceCumulativeUSDC;
timeOfTWAPInit = blockTimestamp;
}
/** @notice Activates rebasing
* @dev One way function, cannot be undone, callable by anyone
*/
function activate_rebasing()
public
{
require(timeOfTWAPInit > 0, "twap wasnt intitiated, call init_twap()");
// cannot enable prior to end of rebaseDelay
require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay");
rebasingActive = true;
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is 1e18
*/
function rebase()
public
{
// EOA only or gov
require(msg.sender == tx.origin, "!EOA");
// ensure rebasing at correct time
_inRebaseWindow();
// This comparison also ensures there is no reentrancy.
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now);
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = now.sub(
now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
// get twap from uniswap v2;
uint256 exchangeRate = getTWAP();
// calculates % change to supply
(uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate);
uint256 indexDelta = offPegPerc;
// Apply the Dampening factor.
indexDelta = indexDelta.div(rebaseLag);
YAMTokenInterface yam = YAMTokenInterface(yamAddress);
if (positive) {
require(yam.yamsScalingFactor().mul(BASE.add(indexDelta)).div(BASE) < yam.maxScalingFactor(), "new scaling factor will be too big");
}
uint256 currSupply = yam.totalSupply();
uint256 mintAmount;
// reduce indexDelta to account for minting
if (positive) {
uint256 mintPerc = indexDelta.mul(rebaseMintPerc).div(BASE);
indexDelta = indexDelta.sub(mintPerc);
mintAmount = currSupply.mul(mintPerc).div(BASE);
}
// rebase
// ignore returned var
yam.rebase(epoch, indexDelta, positive);
// perform actions after rebase
emit MintAmount(mintAmount);
afterRebase(mintAmount, offPegPerc);
}
function uniswapV2Call(
address sender,
uint256 amount0,
uint256 amount1,
bytes memory data
)
public
{
// enforce that it is coming from uniswap
require(msg.sender == trade_pair, "bad msg.sender");
// enforce that this contract called uniswap
require(sender == address(this), "bad origin");
(UniVars memory uniVars) = abi.decode(data, (UniVars));
YAMTokenInterface yam = YAMTokenInterface(yamAddress);
if (uniVars.amountFromReserves > 0) {
// transfer from reserves and mint to uniswap
yam.transferFrom(reservesContract, trade_pair, uniVars.amountFromReserves);
if (uniVars.amountFromReserves < uniVars.yamsToUni) {
// if the amount from reserves > yamsToUni, we have fully paid for the yCRV tokens
// thus this number would be 0 so no need to mint
yam.mint(trade_pair, uniVars.yamsToUni.sub(uniVars.amountFromReserves));
}
} else {
// mint to uniswap
yam.mint(trade_pair, uniVars.yamsToUni);
}
// mint unsold to mintAmount
if (uniVars.mintToReserves > 0) {
yam.mint(reservesContract, uniVars.mintToReserves);
}
// transfer reserve token to reserves
if (isToken0) {
if (public_goods != address(0) && public_goods_perc > 0) {
uint256 amount_to_public_goods = amount1.mul(public_goods_perc).div(BASE);
SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount1.sub(amount_to_public_goods));
SafeERC20.safeTransfer(IERC20(reserveToken), public_goods, amount_to_public_goods);
emit TreasuryIncreased(
amount1.sub(amount_to_public_goods),
uniVars.yamsToUni,
uniVars.amountFromReserves,
uniVars.mintToReserves
);
} else {
SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount1);
emit TreasuryIncreased(
amount1,
uniVars.yamsToUni,
uniVars.amountFromReserves,
uniVars.mintToReserves
);
}
} else {
if (public_goods != address(0) && public_goods_perc > 0) {
uint256 amount_to_public_goods = amount0.mul(public_goods_perc).div(BASE);
SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount0.sub(amount_to_public_goods));
SafeERC20.safeTransfer(IERC20(reserveToken), public_goods, amount_to_public_goods);
emit TreasuryIncreased(
amount0.sub(amount_to_public_goods),
uniVars.yamsToUni,
uniVars.amountFromReserves,
uniVars.mintToReserves
);
} else {
SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount0);
emit TreasuryIncreased(
amount0,
uniVars.yamsToUni,
uniVars.amountFromReserves,
uniVars.mintToReserves
);
}
}
}
function buyReserveAndTransfer(
uint256 mintAmount,
uint256 offPegPerc
)
internal
{
UniswapPair pair = UniswapPair(trade_pair);
YAMTokenInterface yam = YAMTokenInterface(yamAddress);
// get reserves
(uint256 token0Reserves, uint256 token1Reserves, ) = pair.getReserves();
// check if protocol has excess yam in the reserve
uint256 excess = yam.balanceOf(reservesContract);
uint256 tokens_to_max_slippage = uniswapMaxSlippage(token0Reserves, token1Reserves, offPegPerc);
UniVars memory uniVars = UniVars({
yamsToUni: tokens_to_max_slippage, // how many yams uniswap needs
amountFromReserves: excess, // how much of yamsToUni comes from reserves
mintToReserves: 0 // how much yams protocol mints to reserves
});
// tries to sell all mint + excess
// falls back to selling some of mint and all of excess
// if all else fails, sells portion of excess
// upon pair.swap, `uniswapV2Call` is called by the uniswap pair contract
if (isToken0) {
if (tokens_to_max_slippage > mintAmount.add(excess)) {
// we already have performed a safemath check on mintAmount+excess
// so we dont need to continue using it in this code path
// can handle selling all of reserves and mint
uint256 buyTokens = getAmountOut(mintAmount + excess, token0Reserves, token1Reserves);
uniVars.yamsToUni = mintAmount + excess;
uniVars.amountFromReserves = excess;
// call swap using entire mint amount and excess; mint 0 to reserves
pair.swap(0, buyTokens, address(this), abi.encode(uniVars));
} else {
if (tokens_to_max_slippage > excess) {
// uniswap can handle entire reserves
uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves);
// swap up to slippage limit, taking entire yam reserves, and minting part of total
uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess));
pair.swap(0, buyTokens, address(this), abi.encode(uniVars));
} else {
// uniswap cant handle all of excess
uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves);
uniVars.amountFromReserves = tokens_to_max_slippage;
uniVars.mintToReserves = mintAmount;
// swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount
// to reserves
pair.swap(0, buyTokens, address(this), abi.encode(uniVars));
}
}
} else {
if (tokens_to_max_slippage > mintAmount.add(excess)) {
// can handle all of reserves and mint
uint256 buyTokens = getAmountOut(mintAmount + excess, token1Reserves, token0Reserves);
uniVars.yamsToUni = mintAmount + excess;
uniVars.amountFromReserves = excess;
// call swap using entire mint amount and excess; mint 0 to reserves
pair.swap(buyTokens, 0, address(this), abi.encode(uniVars));
} else {
if (tokens_to_max_slippage > excess) {
// uniswap can handle entire reserves
uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves);
// swap up to slippage limit, taking entire yam reserves, and minting part of total
uniVars.mintToReserves = mintAmount.sub( (tokens_to_max_slippage - excess) );
pair.swap(buyTokens, 0, address(this), abi.encode(uniVars));
} else {
// uniswap cant handle all of excess
uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves);
uniVars.amountFromReserves = tokens_to_max_slippage;
uniVars.mintToReserves = mintAmount;
// swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount
// to reserves
pair.swap(buyTokens, 0, address(this), abi.encode(uniVars));
}
}
}
}
function uniswapMaxSlippage(
uint256 token0,
uint256 token1,
uint256 offPegPerc
)
internal
view
returns (uint256)
{
if (isToken0) {
if (offPegPerc >= 10**17) {
// cap slippage
return token0.mul(maxSlippageFactor).div(BASE);
} else {
// in the 5-10% off peg range, slippage is essentially 2*x (where x is percentage of pool to buy).
// all we care about is not pushing below the peg, so underestimate
// the amount we can sell by dividing by 3. resulting price impact
// should be ~= offPegPerc * 2 / 3, which will keep us above the peg
//
// this is a conservative heuristic
return token0.mul(offPegPerc).div(3 * BASE);
}
} else {
if (offPegPerc >= 10**17) {
return token1.mul(maxSlippageFactor).div(BASE);
} else {
return token1.mul(offPegPerc).div(3 * BASE);
}
}
}
/**
* @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
*
* @param amountIn input amount of the asset
* @param reserveIn reserves of the asset being sold
* @param reserveOut reserves if the asset being purchased
*/
function getAmountOut(
uint amountIn,
uint reserveIn,
uint reserveOut
)
internal
pure
returns (uint amountOut)
{
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
function afterRebase(
uint256 mintAmount,
uint256 offPegPerc
)
internal
{
// update uniswap pairs
for (uint256 i = 0; i < uniSyncPairs.length; i++) {
UniswapPair(uniSyncPairs[i]).sync();
}
// update balancer pairs
for (uint256 i = 0; i < balGulpPairs.length; i++) {
BAL(balGulpPairs[i]).gulp(yamAddress);
}
if (mintAmount > 0) {
buyReserveAndTransfer(
mintAmount,
offPegPerc
);
}
// call any extra functions
for (uint i = 0; i < transactions.length; i++) {
Transaction storage t = transactions[i];
if (t.enabled) {
bool result =
externalCall(t.destination, t.data);
if (!result) {
emit TransactionFailed(t.destination, i, t.data);
revert("Transaction Failed");
}
}
}
}
/**
* @notice Calculates TWAP from uniswap
*
* @dev When liquidity is low, this can be manipulated by an end of block -> next block
* attack. We delay the activation of rebases 12 hours after liquidity incentives
* to reduce this attack vector. Additional there is very little supply
* to be able to manipulate this during that time period of highest vuln.
*/
function getTWAP()
internal
returns (uint256)
{
(uint priceCumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(trade_pair, isToken0);
(uint priceCumulativeETH, ) =
UniswapV2OracleLibrary.currentCumulativePrices(eth_usdc_pair, false);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// no period check as is done in isRebaseWindow
// overflow is desired
uint256 priceAverageYAMETH = uint256(uint224((priceCumulative - priceCumulativeLastYAMETH) / timeElapsed));
uint256 priceAverageETHUSDC = uint256(uint224((priceCumulativeETH - priceCumulativeLastETHUSDC) / timeElapsed));
priceCumulativeLastYAMETH = priceCumulative;
priceCumulativeLastETHUSDC = priceCumulativeETH;
blockTimestampLast = blockTimestamp;
// BASE is on order of 1e18, which takes 2^60 bits
// multiplication will revert if priceAverage > 2^196
// (which it can because it overflows intentially)
uint256 YAMETHprice;
uint256 ETHprice;
if (priceAverageYAMETH > uint192(-1)) {
// eat loss of precision
// effectively: (x / 2**112) * 1e18
YAMETHprice = (priceAverageYAMETH >> 112) * BASE;
} else {
// cant overflow
// effectively: (x * 1e18 / 2**112)
YAMETHprice = (priceAverageYAMETH * BASE) >> 112;
}
if (priceAverageETHUSDC > uint192(-1)) {
ETHprice = (priceAverageETHUSDC >> 112) * BASE;
} else {
ETHprice = (priceAverageETHUSDC * BASE) >> 112;
}
return YAMETHprice.mul(ETHprice).div(10**6);
}
/**
* @notice Calculates current TWAP from uniswap
*
*/
function getCurrentTWAP()
public
view
returns (uint256)
{
(uint priceCumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(trade_pair, isToken0);
(uint priceCumulativeETH, ) =
UniswapV2OracleLibrary.currentCumulativePrices(eth_usdc_pair, false);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// no period check as is done in isRebaseWindow
uint256 priceAverageYAMETH = uint256(uint224((priceCumulative - priceCumulativeLastYAMETH) / timeElapsed));
uint256 priceAverageETHUSDC = uint256(uint224((priceCumulativeETH - priceCumulativeLastETHUSDC) / timeElapsed));
// BASE is on order of 1e18, which takes 2^60 bits
// multiplication will revert if priceAverage > 2^196
// (which it can because it overflows intentially)
uint256 YAMETHprice;
uint256 ETHprice;
if (priceAverageYAMETH > uint192(-1)) {
// eat loss of precision
// effectively: (x / 2**112) * 1e18
YAMETHprice = (priceAverageYAMETH >> 112) * BASE;
} else {
// cant overflow
// effectively: (x * 1e18 / 2**112)
YAMETHprice = (priceAverageYAMETH * BASE) >> 112;
}
if (priceAverageETHUSDC > uint192(-1)) {
ETHprice = (priceAverageETHUSDC >> 112) * BASE;
} else {
ETHprice = (priceAverageETHUSDC * BASE) >> 112;
}
return YAMETHprice.mul(ETHprice).div(10**6);
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetRate, then no supply
* modifications are made.
* @param deviationThreshold_ The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 deviationThreshold_)
external
onlyGov
{
require(deviationThreshold > 0);
uint256 oldDeviationThreshold = deviationThreshold;
deviationThreshold = deviationThreshold_;
emit NewDeviationThreshold(oldDeviationThreshold, deviationThreshold_);
}
/**
* @notice Sets the rebase lag parameter.
It is used to dampen the applied supply adjustment by 1 / rebaseLag
If the rebase lag R, equals 1, the smallest value for R, then the full supply
correction is applied on each rebase cycle.
If it is greater than 1, then a correction of 1/R of is applied on each rebase.
* @param rebaseLag_ The new rebase lag parameter.
*/
function setRebaseLag(uint256 rebaseLag_)
external
onlyGov
{
require(rebaseLag_ > 0);
rebaseLag = rebaseLag_;
}
/**
* @notice Sets the targetRate parameter.
* @param targetRate_ The new target rate parameter.
*/
function setTargetRate(uint256 targetRate_)
external
onlyGov
{
require(targetRate_ > 0);
targetRate = targetRate_;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase
* operations, in seconds.
* @param rebaseWindowOffsetSec_ The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param rebaseWindowLengthSec_ The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 minRebaseTimeIntervalSec_,
uint256 rebaseWindowOffsetSec_,
uint256 rebaseWindowLengthSec_)
external
onlyGov
{
require(minRebaseTimeIntervalSec_ > 0);
require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_);
require(rebaseWindowOffsetSec_ + rebaseWindowLengthSec_ < minRebaseTimeIntervalSec_);
minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_;
rebaseWindowOffsetSec = rebaseWindowOffsetSec_;
rebaseWindowLengthSec = rebaseWindowLengthSec_;
}
/**
* @return If the latest block timestamp is within the rebase time window it, returns true.
* Otherwise, returns false.
*/
function inRebaseWindow() public view returns (bool) {
// rebasing is delayed until there is a liquid market
_inRebaseWindow();
return true;
}
function _inRebaseWindow() internal view {
// rebasing is delayed until there is a liquid market
require(rebasingActive, "rebasing not active");
require(now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, "too early");
require(now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), "too late");
}
/**
* @return Computes in % how far off market is from peg
*/
function computeOffPegPerc(uint256 rate)
private
view
returns (uint256, bool)
{
if (withinDeviationThreshold(rate)) {
return (0, false);
}
// indexDelta = (rate - targetRate) / targetRate
if (rate > targetRate) {
return (rate.sub(targetRate).mul(BASE).div(targetRate), true);
} else {
return (targetRate.sub(rate).mul(BASE).div(targetRate), false);
}
}
/**
* @param rate The current exchange rate, an 18 decimal fixed point number.
* @return If the rate is within the deviation threshold from the target rate, returns true.
* Otherwise, returns false.
*/
function withinDeviationThreshold(uint256 rate)
private
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
.div(10 ** 18);
return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
|| (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
/* - Constructor Helpers - */
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address token0,
address token1
)
internal
pure
returns (address pair)
{
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
function pairForSushi(
address factory,
address tokenA,
address tokenB
)
internal
pure
returns (address pair)
{
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash
))));
}
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(
address tokenA,
address tokenB
)
internal
pure
returns (address token0, address token1)
{
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
/* -- Rebase helpers -- */
/**
* @notice Adds a transaction that gets called for a downstream receiver of rebases
* @param destination Address of contract destination
* @param data Transaction data payload
*/
function addTransaction(address destination, bytes calldata data)
external
onlyGov
{
transactions.push(Transaction({
enabled: true,
destination: destination,
data: data
}));
}
/**
* @param index Index of transaction to remove.
* Transaction ordering may have changed since adding.
*/
function removeTransaction(uint index)
external
onlyGov
{
require(index < transactions.length, "index out of bounds");
if (index < transactions.length - 1) {
transactions[index] = transactions[transactions.length - 1];
}
transactions.length--;
}
/**
* @param index Index of transaction. Transaction ordering may have changed since adding.
* @param enabled True for enabled, false for disabled.
*/
function setTransactionEnabled(uint index, bool enabled)
external
onlyGov
{
require(index < transactions.length, "index must be in range of stored tx list");
transactions[index].enabled = enabled;
}
/**
* @dev wrapper to call the encoded transactions on downstream consumers.
* @param destination Address of destination contract.
* @param data The encoded data payload.
* @return True on success
*/
function externalCall(address destination, bytes memory data)
internal
returns (bool)
{
bool result;
assembly { // solhint-disable-line no-inline-assembly
// "Allocate" memory for output
// (0x40 is where "free memory" pointer is stored by convention)
let outputAddress := mload(0x40)
// First 32 bytes are the padded length of data, so exclude that
let dataAddress := add(data, 32)
result := call(
// 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB)
// + callValueTransferGas (9000) + callNewAccountGas
// (25000, in case the destination address does not exist and needs creating)
sub(gas, 34710),
destination,
0, // transfer value in wei
dataAddress,
mload(data), // Size of the input, in bytes. Stored in position 0 of the array.
outputAddress,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
// Rescue tokens
function rescueTokens(
address token,
address to,
uint256 amount
)
external
onlyGov
returns (bool)
{
// transfer to
SafeERC20.safeTransfer(IERC20(token), to, amount);
}
}
|
Calculates current TWAP from uniswap/ no period check as is done in isRebaseWindow BASE is on order of 1e18, which takes 2^60 bits multiplication will revert if priceAverage > 2^196 (which it can because it overflows intentially) eat loss of precision effectively: (x / 2112) 1e18 cant overflow effectively: (x 1e18 / 2112)
|
function getCurrentTWAP()
public
view
returns (uint256)
{
(uint priceCumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(trade_pair, isToken0);
(uint priceCumulativeETH, ) =
UniswapV2OracleLibrary.currentCumulativePrices(eth_usdc_pair, false);
uint256 priceAverageYAMETH = uint256(uint224((priceCumulative - priceCumulativeLastYAMETH) / timeElapsed));
uint256 priceAverageETHUSDC = uint256(uint224((priceCumulativeETH - priceCumulativeLastETHUSDC) / timeElapsed));
uint256 YAMETHprice;
uint256 ETHprice;
if (priceAverageYAMETH > uint192(-1)) {
YAMETHprice = (priceAverageYAMETH >> 112) * BASE;
YAMETHprice = (priceAverageYAMETH * BASE) >> 112;
}
if (priceAverageETHUSDC > uint192(-1)) {
ETHprice = (priceAverageETHUSDC >> 112) * BASE;
ETHprice = (priceAverageETHUSDC * BASE) >> 112;
}
return YAMETHprice.mul(ETHprice).div(10**6);
}
| 14,820,205
|
pragma solidity ^0.4.15;
import 'zeppelin-solidity/contracts/token/MintableToken.sol';
/// @title The token for the Home Ethereum's acommodation platform. The totalSupply
/// of tokens gets incremented when tokens are bought
/// @author Merunas Grincalaitis
contract HomeToken is MintableToken {
// Name of the token
string public name;
// Symbol of the token
string public symbol;
// The amount of decimals for that token
uint8 public decimals;
/// @notice Constructor to generate the HomeToken. The `totalSupply` of tokens
/// gets incremented whenever someone buys tokens on the crowdsale
/// @param _name The name of the token
/// @param _symbol The symbol of the token
/// @param _decimals The decimals of the token
/// @param initialSupply The initial amount of tokens created that will go to
/// the creator of the token and will be the `totalSupply` because it's a `MintableToken`
function HomeToken(string _name, string _symbol, uint8 _decimals, uint initialSupply) {
require(bytes(_name).length > 0);
require(bytes(_symbol).length > 0);
require(_decimals > 0);
require(initialSupply > 0);
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = initialSupply;
// The creator of the token gets the initial supply
balances[msg.sender] = initialSupply;
}
}
|
Constructor to generate the HomeToken. The `totalSupply` of tokens gets incremented whenever someone buys tokens on the crowdsale _name The name of the token _symbol The symbol of the token _decimals The decimals of the token initialSupply The initial amount of tokens created that will go to the creator of the token and will be the `totalSupply` because it's a `MintableToken` The creator of the token gets the initial supply
|
function HomeToken(string _name, string _symbol, uint8 _decimals, uint initialSupply) {
require(bytes(_name).length > 0);
require(bytes(_symbol).length > 0);
require(_decimals > 0);
require(initialSupply > 0);
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
}
| 7,231,740
|
pragma solidity ^0.5.0;
library SafeMath {
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a);
return c;
}
/*function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b);
return c;
}*/
}
contract ERC20Basic {
uint public totalSupply;
address public owner; //owner
function balanceOf(address who) public view returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
function commitDividend(address who) public; // pays remaining dividend
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint;
// users
struct User {
uint120 tokens; // current tokens of user
uint120 asks; // current tokens in asks
uint120 votes; // current voting power
uint120 weis; // current wei balance of user
uint32 lastProposalID; // last processed dividend period of user's tokens
address owner; // votes for new owner
uint8 voted; // vote for proposal
}
mapping (address => User) users;
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
/**
* @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, uint _value) public onlyPayloadSize(2 * 32) {
commitDividend(msg.sender);
users[msg.sender].tokens = uint120(uint(users[msg.sender].tokens).sub(_value));
if(_to == address(this)) {
commitDividend(owner);
users[owner].tokens = uint120(uint(users[owner].tokens).add(_value));
emit Transfer(msg.sender, owner, _value);
}
else {
commitDividend(_to);
users[_to].tokens = uint120(uint(users[_to].tokens).add(_value));
emit Transfer(msg.sender, _to, _value);
}
}
/**
* @dev Gets the amount of tokens
* @param _owner The address to query.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint) {
return uint(users[_owner].tokens);
}
/**
* @dev Gets the amount of tokens offered for sale (in asks)
* @param _owner The address to query.
* @return An uint representing the amount offered by the passed address.
*/
function askOf(address _owner) public view returns (uint) {
return uint(users[_owner].asks);
}
/**
* @dev Gets the amount of tokens offered for sale (in asks)
* @param _owner The address to query.
* @return An uint representing the amount offered by the passed address.
*/
function voteOf(address _owner) public view returns (uint) {
return uint(users[_owner].votes);
}
/**
* @dev Gets the amount of wei owned by user and stored in contract
* @param _owner The address to query.
* @return An uint representing the amount wei stored in contract.
*/
function weiOf(address _owner) public view returns (uint) {
return uint(users[_owner].weis);
}
/**
* @dev Gets the id of last proccesed proposal period
* @param _owner The address to query.
* @return An uint representing the id of last processed proposal period
*/
function lastOf(address _owner) public view returns (uint) {
return uint(users[_owner].lastProposalID);
}
/**
* @dev Gets the proposed address of new contract owner / manager
* @param _owner The address to query.
* @return An address proposed as new contract owner / manager
*/
function ownerOf(address _owner) public view returns (address) {
return users[_owner].owner;
}
/**
* @dev Gets the status of voting
* @param _owner The address to query.
* @return An uint > 0 if user already voted
*/
function votedOf(address _owner) public view returns (uint) {
return uint(users[_owner].voted);
}
}
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) 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 uint the amount of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
uint _allowance = allowed[_from][msg.sender];
commitDividend(_from);
commitDividend(_to);
allowed[_from][msg.sender] = _allowance.sub(_value);
users[_from].tokens = uint120(uint(users[_from].tokens).sub(_value));
users[_to].tokens = uint120(uint(users[_to].tokens).add(_value));
emit Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) public {
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
assert(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than 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 uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title PicoStocksAsset contract
*/
contract PicoStocksAsset is StandardToken {
// metadata
string public constant name = "PicoStocks Asset";
uint public constant decimals = 0;
uint public picoid = 0; // Asset ID on PicoStocks
string public symbol = ""; // Asset code on PicoStocks
string public www = ""; // Official web page
uint public totalWeis = 0; // sum of wei owned by users
uint public totalVotes = 0; // number of alligible votes
struct Order {
uint64 prev; // previous order, need this to enable safe/fast order cancel
uint64 next; // next order
uint128 price; // offered/requested price of 1 token
uint96 amount; // number of offered/requested tokens
address who; // address of owner of tokens or funds
}
mapping (uint => Order) asks;
mapping (uint => Order) bids;
uint64 firstask=0; // key of lowest ask
uint64 lastask=0; // key of last inserted ask
uint64 firstbid=0; // key of highest bid
uint64 lastbid=0; // key of last inserted bid
uint constant weekBlocks = 4*60*24*7; // number of blocks in 1 week
uint constant minPrice = 0xFFFF; // min price per token
uint constant maxPrice = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // max price per token
uint constant maxTokens = 0xFFFFFFFFFFFFFFFFFFFFFFFF; // max number of tokens
address public custodian = 0xd720a4768CACE6d508d8B390471d83BA3aE6dD32;
// investment parameters
uint public investPrice; // price of 1 token
uint public investStart; // first block of funding round
uint public investEnd; // last block of funding round
uint public investGot; // funding collected
uint public investMin; // minimum funding
uint public investMax; // maximum funding
uint public investKYC = 1; // KYC requirement
//dividends
uint[] public dividends; // dividens collected per period, growing array
//proposal
uint public proposalID = 1; // proposal number and dividend period
uint public proposalVotesYes; // yes-votes collected
uint public proposalVotesNo; // no-votes collected
uint public proposalBlock; // block number proposal published
uint public proposalDividendPerShare; // dividend per share
uint public proposalBudget; // budget for the owner for next period
uint public proposalTokens; // number of new tokens for next round
uint public proposalPrice; // price of new token in next round
uint public acceptedBudget; // unspent budget for the owner in current round
//change owner
mapping (address => uint) owners; // votes for new owners / managers of the contract
// events
event LogBuy(address indexed who, uint amount, uint price);
event LogSell(address indexed who, uint amount, uint price);
event LogCancelBuy(address indexed who, uint amount, uint price);
event LogCancelSell(address indexed who, uint amount, uint price);
event LogTransaction(address indexed from, address indexed to, uint amount, uint price);
event LogDeposit(address indexed who,uint amount);
event LogWithdraw(address indexed who,uint amount);
event LogExec(address indexed who,uint amount);
event LogPayment(address indexed who, address from, uint amount);
event LogDividend(uint amount);
event LogDividend(address indexed who, uint amount, uint period);
event LogNextInvestment(uint price,uint amount);
event LogNewOwner(address indexed who);
event LogNewCustodian(address indexed who);
event LogNewWww(string www);
event LogProposal(uint dividendpershare,uint budget,uint moretokens,uint minprice);
event LogVotes(uint proposalVotesYes,uint proposalVotesNo);
event LogBudget(uint proposalBudget);
event LogAccepted(uint proposalDividendPerShare,uint proposalBudget,uint proposalTokens,uint proposalPrice);
event LogRejected(uint proposalDividendPerShare,uint proposalBudget,uint proposalTokens,uint proposalPrice);
modifier onlyOwner() {
assert(msg.sender == owner);
_;
}
// constructor
/**
* @dev Contract constructor
*/
constructor() public {
owner = msg.sender;
}
/* initial investment functions */
/**
* @dev Set first funding round parameters
* @param _tokens number of tokens given to admin
* @param _budget initial approved budget
* @param _price price of 1 token in first founding round
* @param _from block number of start of funding round
* @param _to block number of end of funding round
* @param _min minimum number of tokens to sell
* @param _max maximum number of tokens to sell
* @param _kyc require KYC during first investment round
* @param _picoid asset id on picostocks
* @param _symbol asset symmbol on picostocks
*/
function setFirstInvestPeriod(uint _tokens,uint _budget,uint _price,uint _from,uint _to,uint _min,uint _max,uint _kyc,uint _picoid,string memory _symbol) public onlyOwner {
require(investPrice == 0 && block.number < _from && _from < _to && _to < _from + weekBlocks*12 && _price > minPrice && _price < maxPrice && _max > 0 && _max > _min && _max < maxTokens );
if(_tokens==0){
_tokens=1;
}
totalSupply = _tokens;
acceptedBudget = _budget;
users[owner].tokens = uint120(_tokens);
users[owner].lastProposalID = uint32(proposalID);
users[custodian].lastProposalID = uint32(proposalID);
investPrice = _price;
investStart = _from;
investEnd = _to;
investMin = _min;
investMax = _max;
investKYC = _kyc;
picoid = _picoid;
symbol = _symbol;
dividends.push(0); // not used
dividends.push(0); // current dividend
}
/**
* @dev Accept address for first investment
* @param _who accepted address (investor)
*/
function acceptKYC(address _who) external onlyOwner {
if(users[_who].lastProposalID==0){
users[_who].lastProposalID=1;
}
}
/**
* @dev Buy tokens
*/
function invest() payable public {
commitDividend(msg.sender);
require(msg.value > 0 && block.number >= investStart && block.number < investEnd && totalSupply < investMax && investPrice > 0);
uint tokens = msg.value / investPrice;
if(investMax < totalSupply.add(tokens)){
tokens = investMax.sub(totalSupply);
}
totalSupply += tokens;
users[msg.sender].tokens += uint120(tokens);
emit Transfer(address(0),msg.sender,tokens);
uint _value = msg.value.sub(tokens * investPrice);
if(_value > 0){ // send back excess funds immediately
emit LogWithdraw(msg.sender,_value);
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(_value)("");
require(success);
}
if(totalSupply>=investMax){
closeInvestPeriod();
}
}
/**
* @dev Buy tokens
*/
function () payable external {
invest();
}
/**
* @dev Return wei to token owners if first funding round failes
*/
function disinvest() public {
require(0 < investEnd && investEnd < block.number && totalSupply < investMin);
payDividend((address(this).balance-totalWeis)/totalSupply); //CHANGED
investEnd += weekBlocks*4; // enable future dividend payment if contract has funds
}
/* management functions */
/**
* @dev Propose dividend, budget and optional funding parameters for next round
* @param _dividendpershare amount of wei per share to pay out
* @param _budget amount of wei to give to owner
* @param _tokens amount of new tokens to issue
* @param _price price of 1 new token
*/
function propose(uint _dividendpershare,uint _budget,uint _tokens,uint _price) external onlyOwner {
require(proposalBlock + weekBlocks*4 < block.number && 0 < investEnd && investEnd < block.number); //can not send more than 1 proposal per 28 days
if(block.number>investEnd && investStart>0 && investPrice>0 && investMax>0){
totalVotes=totalSupply;
investStart=0;
investMax=0;
}
proposalVotesYes=0;
proposalVotesNo=0;
proposalID=proposalID+1;
dividends.push(0);
proposalBlock=block.number;
proposalDividendPerShare=_dividendpershare;
proposalBudget=_budget;
proposalTokens=_tokens;
proposalPrice=_price;
emit LogProposal(_dividendpershare,_budget,_tokens,_price);
}
/**
* @dev Execute proposed plan if passed
*/
function executeProposal() public {
require(proposalVotesYes > 0 && (proposalBlock + weekBlocks*4 < block.number || proposalVotesYes>totalVotes/2 || proposalVotesNo>totalVotes/2));
//old require(proposalVotesYes > 0);
emit LogVotes(proposalVotesYes,proposalVotesNo);
if(proposalVotesYes >= proposalVotesNo && (proposalTokens==0 || proposalPrice>=investPrice || proposalVotesYes>totalVotes/2)){
if(payDividend(proposalDividendPerShare) > 0){
emit LogBudget(proposalBudget);
acceptedBudget=proposalBudget;}
if(proposalTokens>0){
emit LogNextInvestment(proposalPrice,proposalTokens);
setNextInvestPeriod(proposalPrice,proposalTokens);}
emit LogAccepted(proposalDividendPerShare,proposalBudget,proposalTokens,proposalPrice);}
else{
emit LogRejected(proposalDividendPerShare,proposalBudget,proposalTokens,proposalPrice);}
proposalBlock=0;
proposalVotesYes=0;
proposalVotesNo=0;
proposalDividendPerShare=0;
proposalBudget=0;
proposalTokens=0;
proposalPrice=0;
}
/**
* @dev Set next funding round parameters
* @param _price price of 1 new token
* @param _tokens amount of new tokens to issue
*/
function setNextInvestPeriod(uint _price,uint _tokens) internal {
require(totalSupply >= investMin && _price < maxPrice && totalSupply + _tokens < 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
investStart = block.number + weekBlocks*2;
investEnd = block.number + weekBlocks*4;
investPrice = _price; // too high price will disable future investments
investMax = totalSupply + _tokens;
investKYC=0;
}
/**
* @dev Finish funding round and update voting power
*/
function closeInvestPeriod() public {
require((block.number>investEnd || totalSupply>=investMax) && investStart>0 && investPrice>0 && investMax>0);
proposalID ++ ;
dividends.push(0);
totalVotes=totalSupply;
investStart=0;
investMax=0;
investKYC=0;
}
/**
* @dev Pay dividend per share
* @param _wei The amount of wei to pay per share
*/
function payDividend(uint _wei) internal returns (uint) {
if(_wei == 0){
return 1;}
//uint newdividend = _wei.mul(totalSupply);
uint newdividend = _wei * totalSupply;
require(newdividend / _wei == totalSupply);
if(address(this).balance < newdividend.add(totalWeis)){
emit LogDividend(0); //indicates failure
return 0;}
totalWeis += newdividend;
dividends[proposalID] = _wei;
proposalID ++ ;
dividends.push(0);
totalVotes=totalSupply;
emit LogDividend(_wei);
return(_wei);
}
/**
* @dev Commit remaining dividends and update votes before transfer of tokens
* @param _who User to process
*/
function commitDividend(address _who) public {
uint last = users[_who].lastProposalID;
require(investKYC==0 || last>0); // only authorized investors during KYC period
uint tokens=users[_who].tokens+users[_who].asks;
if((tokens==0) || (last==0)){
users[_who].lastProposalID=uint32(proposalID);
return;
}
if(last==proposalID) {
return;
}
if(tokens != users[_who].votes){
if(users[_who].owner != address(0)){
owners[users[_who].owner] = owners[users[_who].owner].add(tokens).sub(uint(users[_who].votes));
}
users[_who].votes=uint120(tokens); // store voting power
}
uint balance = 0;
for(; last < proposalID ; last ++) {
balance += tokens * dividends[last];
}
users[_who].weis += uint120(balance);
users[_who].lastProposalID = uint32(last);
users[_who].voted=0;
emit LogDividend(_who,balance,last);
}
/* administrative functions */
/**
* @dev Change owner
* @param _who The address of new owner
*/
function changeOwner(address _who) external onlyOwner {
assert(_who != address(0));
owner = _who;
emit LogNewOwner(_who);
}
/**
* @dev Change the official www address
* @param _www The new www address
*/
function changeWww(string calldata _www) external onlyOwner {
www=_www;
emit LogNewWww(_www);
}
/**
* @dev Change owner
* @param _who The address of new owner
*/
function changeCustodian(address _who) external { //CHANGED
assert(msg.sender == custodian);
assert(_who != address(0));
custodian = _who;
emit LogNewCustodian(_who);
}
/**
* @dev Execute a call
* @param _to destination address
* @param _data The call data
*/
function exec(address _to,bytes calldata _data) payable external onlyOwner {
emit LogExec(_to,msg.value);
(bool success, /*bytes memory _unused*/) =_to.call.value(msg.value)(_data);
require(success);
}
/**
* @dev Withdraw funds from contract by contract owner / manager
* @param _amount The amount of wei to withdraw
* @param _who The addres to send wei to
*/
function spend(uint _amount,address _who) external onlyOwner {
require(_amount > 0 && address(this).balance >= _amount.add(totalWeis) && totalSupply >= investMin);
acceptedBudget=acceptedBudget.sub(_amount); //check for excess withdrawal
if(_who == address(0)){
emit LogWithdraw(msg.sender,_amount);
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(_amount)("");
require(success);}
else{
emit LogWithdraw(_who,_amount);
(bool success, /*bytes memory _unused*/) = _who.call.value(_amount)("");
require(success);}
}
/* user functions */
/**
* @dev Vote to change contract owner / manager
* @param _who The addres of the proposed new contract owner / manager
*/
function voteOwner(address _who) external {
require(_who != users[msg.sender].owner);
if(users[msg.sender].owner != address(0)){
owners[users[msg.sender].owner] = owners[users[msg.sender].owner].sub(users[msg.sender].votes);
}
users[msg.sender].owner=_who;
if(_who != address(0)){
owners[_who] = owners[_who].add(users[msg.sender].votes);
if(owners[_who] > totalVotes/2 && _who != owner){
owner = _who;
emit LogNewOwner(_who);
}
}
}
/**
* @dev Vote in favor of the current proposal
*/
function voteYes() public {
commitDividend(msg.sender);
require(users[msg.sender].voted == 0 && proposalBlock + weekBlocks*4 > block.number && proposalBlock > 0);
users[msg.sender].voted=1;
proposalVotesYes+=users[msg.sender].votes;
}
/**
* @dev Vote against the current proposal
*/
function voteNo() public {
commitDividend(msg.sender);
require(users[msg.sender].voted == 0 && proposalBlock + weekBlocks*4 > block.number && proposalBlock > 0);
users[msg.sender].voted=1;
proposalVotesNo+=users[msg.sender].votes;
}
/**
* @dev Vote in favor of the proposal defined by ID
* @param _id Proposal ID
*/
function voteYes(uint _id) external {
require(proposalID==_id);
voteYes();
}
/**
* @dev Vote against the proposal defined by ID
* @param _id Proposal ID
*/
function voteNo(uint _id) external {
require(proposalID==_id);
voteNo();
}
/**
* @dev Store funds in contract
*/
function deposit() payable external {
commitDividend(msg.sender); //CHANGED
users[msg.sender].weis += uint120(msg.value);
totalWeis += msg.value;
emit LogDeposit(msg.sender,msg.value);
}
/**
* @dev Withdraw funds from contract
* @param _amount Amount of wei to withdraw
*/
function withdraw(uint _amount) external {
commitDividend(msg.sender);
uint amount=_amount;
if(amount > 0){
require(users[msg.sender].weis >= amount);
}
else{
require(users[msg.sender].weis > 0);
amount=users[msg.sender].weis;
}
users[msg.sender].weis = uint120(uint(users[msg.sender].weis).sub(amount));
totalWeis = totalWeis.sub(amount);
//msg.sender.transfer(amount);
emit LogWithdraw(msg.sender,amount);
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(amount)("");
require(success);
}
/**
* @dev Wire funds from one user to another user
* @param _amount Amount of wei to wire
* @param _who Address of the user to wire to
*/
function wire(uint _amount,address _who) external {
users[msg.sender].weis = uint120(uint(users[msg.sender].weis).sub(_amount));
users[_who].weis = uint120(uint(users[_who].weis).add(_amount));
}
/**
* @dev Send wei to contract
* @param _who Address of the payee
*/
function pay(address _who) payable external {
emit LogPayment(_who,msg.sender,msg.value);
}
/* market view functions */
/**
* @dev Return ask orders optionally filtered by user
* @param _who Optional address of the user
* @return An array of uint representing the (filtered) orders, 4 uints per order (id,price,amount,user)
*/
function ordersSell(address _who) external view returns (uint[256] memory) {
uint[256] memory ret;
uint num=firstask;
uint id=0;
for(;asks[num].price>0 && id<64;num=uint(asks[num].next)){
if(_who!=address(0) && _who!=asks[num].who){
continue;
}
ret[4*id+0]=num;
ret[4*id+1]=uint(asks[num].price);
ret[4*id+2]=uint(asks[num].amount);
ret[4*id+3]=uint(asks[num].who);
id++;}
return ret;
}
/**
* @dev Return bid orders optionally filtered by user
* @param _who Optional address of the user
* @return An array of uint representing the (filtered) orders, 4 uints per order (id,price,amount,user)
*/
function ordersBuy(address _who) external view returns (uint[256] memory) {
uint[256] memory ret;
uint num=firstbid;
uint id=0;
for(;bids[num].price>0 && id<64;num=uint(bids[num].next)){
if(_who!=address(0) && _who!=bids[num].who){
continue;
}
ret[4*id+0]=num;
ret[4*id+1]=uint(bids[num].price);
ret[4*id+2]=uint(bids[num].amount);
ret[4*id+3]=uint(bids[num].who);
id++;}
return ret;
}
/**
* @dev Find the ask order id for a user
* @param _who The address of the user
* @param _minprice Optional minimum price
* @param _maxprice Optional maximum price
* @return The id of the order
*/
function findSell(address _who,uint _minprice,uint _maxprice) external view returns (uint) {
uint num=firstask;
for(;asks[num].price>0;num=asks[num].next){
if(_maxprice > 0 && asks[num].price > _maxprice){
return 0;}
if(_minprice > 0 && asks[num].price < _minprice){
continue;}
if(_who == asks[num].who){ //FIXED !!!
return num;}}
}
/**
* @dev Find the bid order id for a user
* @param _who The address of the user
* @param _minprice Optional minimum price
* @param _maxprice Optional maximum price
* @return The id of the order
*/
function findBuy(address _who,uint _minprice,uint _maxprice) external view returns (uint) {
uint num=firstbid;
for(;bids[num].price>0;num=bids[num].next){
if(_minprice > 0 && bids[num].price < _minprice){
return 0;}
if(_maxprice > 0 && bids[num].price > _maxprice){
continue;}
if(_who == bids[num].who){
return num;}}
}
/**
* @dev Report the user address of an ask order
* @param _id The id of the order
* @return The address of the user placing the order
*/
function whoSell(uint _id) external view returns (address) {
if(_id>0){
return address(asks[_id].who);
}
return address(asks[firstask].who);
}
/**
* @dev Report the user address of a bid order
* @param _id The id of the order
* @return The address of the user placing the order
*/
function whoBuy(uint _id) external view returns (address) {
if(_id>0){
return address(bids[_id].who);
}
return address(bids[firstbid].who);
}
/**
* @dev Report the amount of tokens of an ask order
* @param _id The id of the order
* @return The amount of tokens offered
*/
function amountSell(uint _id) external view returns (uint) {
if(_id>0){
return uint(asks[_id].amount);
}
return uint(asks[firstask].amount);
}
/**
* @dev Report the amount of tokens of a bid order
* @param _id The id of the order
* @return The amount of tokens requested
*/
function amountBuy(uint _id) external view returns (uint) {
if(_id>0){
return uint(bids[_id].amount);
}
return uint(bids[firstbid].amount);
}
/**
* @dev Report the price of 1 token of an ask order
* @param _id The id of the order
* @return The requested price for 1 token
*/
function priceSell(uint _id) external view returns (uint) {
if(_id>0){
return uint(asks[_id].price);
}
return uint(asks[firstask].price);
}
/**
* @dev Report the price of 1 token of a bid order
* @param _id The id of the order
* @return The offered price for 1 token
*/
function priceBuy(uint _id) external view returns (uint) {
if(_id>0){
return uint(bids[_id].price);
}
return uint(bids[firstbid].price);
}
/* trade functions */
/**
* @dev Cancel an ask order
* @param _id The id of the order
*/
function cancelSell(uint _id) external {
require(asks[_id].price>0 && asks[_id].who==msg.sender);
users[msg.sender].tokens=uint120(uint(users[msg.sender].tokens).add(asks[_id].amount));
users[msg.sender].asks=uint120(uint(users[msg.sender].asks).sub(asks[_id].amount));
if(asks[_id].prev>0){
asks[asks[_id].prev].next=asks[_id].next;}
else{
firstask=asks[_id].next;}
if(asks[_id].next>0){
asks[asks[_id].next].prev=asks[_id].prev;}
emit LogCancelSell(msg.sender,asks[_id].amount,asks[_id].price);
delete(asks[_id]);
}
/**
* @dev Cancel a bid order
* @param _id The id of the order
*/
function cancelBuy(uint _id) external {
require(bids[_id].price>0 && bids[_id].who==msg.sender);
uint value=bids[_id].amount*bids[_id].price;
users[msg.sender].weis+=uint120(value);
if(bids[_id].prev>0){
bids[bids[_id].prev].next=bids[_id].next;}
else{
firstbid=bids[_id].next;}
if(bids[_id].next>0){
bids[bids[_id].next].prev=bids[_id].prev;}
emit LogCancelBuy(msg.sender,bids[_id].amount,bids[_id].price);
delete(bids[_id]);
}
/**
* @dev Place and ask order (sell tokens)
* @param _amount The amount of tokens to sell
* @param _price The minimum price per token in wei
*/
function sell(uint _amount, uint _price) external {
require(0 < _price && _price < maxPrice && 0 < _amount && _amount < maxTokens && _amount <= users[msg.sender].tokens);
commitDividend(msg.sender);
users[msg.sender].tokens-=uint120(_amount); //we will sell that much
uint funds=0;
uint amount=_amount;
for(;bids[firstbid].price>0 && bids[firstbid].price>=_price;){
uint value=uint(bids[firstbid].price)*uint(bids[firstbid].amount);
uint fee=value >> 9; //0.4% fee
if(amount>=bids[firstbid].amount){
amount=amount.sub(uint(bids[firstbid].amount));
commitDividend(bids[firstbid].who);
emit LogTransaction(msg.sender,bids[firstbid].who,bids[firstbid].amount,bids[firstbid].price);
//seller
//users[msg.sender].tokens-=bids[firstbid].amount;
funds=funds.add(value-fee-fee);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.sub(fee);
//buyer
users[bids[firstbid].who].tokens+=bids[firstbid].amount;
//clear
uint64 next=bids[firstbid].next;
delete bids[firstbid];
firstbid=next; // optimize and move outside ?
if(amount==0){
break;}
continue;}
value=amount*uint(bids[firstbid].price);
fee=value >> 9; //0.4% fee
commitDividend(bids[firstbid].who);
funds=funds.add(value-fee-fee);
emit LogTransaction(msg.sender,bids[firstbid].who,amount,bids[firstbid].price);
//seller
//users[msg.sender].tokens-=amount;
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.sub(fee);
bids[firstbid].amount=uint96(uint(bids[firstbid].amount).sub(amount));
require(bids[firstbid].amount>0);
//buyer
users[bids[firstbid].who].tokens+=uint120(amount);
bids[firstbid].prev=0;
totalWeis=totalWeis.sub(funds);
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(funds)("");
require(success);
return;}
if(firstbid>0){
bids[firstbid].prev=0;}
if(amount>0){
uint64 ask=firstask;
uint64 last=0;
for(;asks[ask].price>0 && asks[ask].price<=_price;ask=asks[ask].next){
last=ask;}
lastask++;
asks[lastask].prev=last;
asks[lastask].next=ask;
asks[lastask].price=uint128(_price);
asks[lastask].amount=uint96(amount);
asks[lastask].who=msg.sender;
users[msg.sender].asks+=uint120(amount);
emit LogSell(msg.sender,amount,_price);
if(last>0){
asks[last].next=lastask;}
else{
firstask=lastask;}
if(ask>0){
asks[ask].prev=lastask;}}
if(funds>0){
totalWeis=totalWeis.sub(funds);
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(funds)("");
require(success);}
}
/**
* @dev Place and bid order (buy tokens using Ether of the transaction)
* @param _amount The maximum amount of tokens to buy
* @param _price The maximum price per token in wei
*/
function buy(uint _amount, uint _price) payable external {
require(0 < _price && _price < maxPrice && 0 < _amount && _amount < maxTokens && _price <= msg.value);
commitDividend(msg.sender);
uint funds=msg.value;
uint amount=_amount;
uint value;
for(;asks[firstask].price>0 && asks[firstask].price<=_price;){
value=uint(asks[firstask].price)*uint(asks[firstask].amount);
uint fee=value >> 9; //2*0.4% fee
if(funds>=value+fee+fee && amount>=asks[firstask].amount){
amount=amount.sub(uint(asks[firstask].amount));
commitDividend(asks[firstask].who);
funds=funds.sub(value+fee+fee);
emit LogTransaction(asks[firstask].who,msg.sender,asks[firstask].amount,asks[firstask].price);
//seller
users[asks[firstask].who].asks-=asks[firstask].amount;
users[asks[firstask].who].weis+=uint120(value);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.add(value+fee);
//buyer
users[msg.sender].tokens+=asks[firstask].amount;
//clear
uint64 next=asks[firstask].next;
delete asks[firstask];
firstask=next; // optimize and move outside ?
if(funds<asks[firstask].price){
break;}
continue;}
if(amount>asks[firstask].amount){
amount=asks[firstask].amount;}
if((funds-(funds>>8))<amount*asks[firstask].price){
amount=(funds-(funds>>8))/asks[firstask].price;}
if(amount>0){
value=amount*uint(asks[firstask].price);
fee=value >> 9; //2*0.4% fee
commitDividend(asks[firstask].who);
funds=funds.sub(value+fee+fee);
emit LogTransaction(asks[firstask].who,msg.sender,amount,asks[firstask].price);
//seller
users[asks[firstask].who].asks-=uint120(amount);
users[asks[firstask].who].weis+=uint120(value);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.add(value+fee);
asks[firstask].amount=uint96(uint(asks[firstask].amount).sub(amount));
require(asks[firstask].amount>0);
//buyer
users[msg.sender].tokens+=uint120(amount);}
asks[firstask].prev=0;
if(funds>0){
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(funds)("");
require(success);}
return;}
if(firstask>0){ //all orders removed
asks[firstask].prev=0;}
if(amount>funds/_price){
amount=funds/_price;}
if(amount>0){
uint64 bid=firstbid;
uint64 last=0;
for(;bids[bid].price>0 && bids[bid].price>=_price;bid=bids[bid].next){
last=bid;}
lastbid++;
bids[lastbid].prev=last;
bids[lastbid].next=bid;
bids[lastbid].price=uint128(_price);
bids[lastbid].amount=uint96(amount);
bids[lastbid].who=msg.sender;
value=amount*_price;
totalWeis=totalWeis.add(value);
funds=funds.sub(value);
emit LogBuy(msg.sender,amount,_price);
if(last>0){
bids[last].next=lastbid;}
else{
firstbid=lastbid;}
if(bid>0){
bids[bid].prev=lastbid;}}
if(funds>0){
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(funds)("");
require(success);}
}
}
|
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint the amount of tokens to be transfered/
|
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
uint _allowance = allowed[_from][msg.sender];
commitDividend(_from);
commitDividend(_to);
allowed[_from][msg.sender] = _allowance.sub(_value);
users[_from].tokens = uint120(uint(users[_from].tokens).sub(_value));
users[_to].tokens = uint120(uint(users[_to].tokens).add(_value));
emit Transfer(_from, _to, _value);
}
| 906,956
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable {
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @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 override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @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 override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
// 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.7;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "./access/GovernanceAccessControl.sol";
import "./interfaces/ICells.sol";
import "./libraries/Array.sol";
contract Cells is ICells, GovernanceAccessControl, ERC721 {
bool public permissionless = false;
bool public pendingPermissionless;
uint256 public maxTokensPerCell = 10;
uint256 public pendingMaxTokensPerCell;
mapping(uint256 => address[]) private _managedTokens;
mapping(uint256 => mapping(address => bool)) private _managedTokensIndex;
uint256 private _topCellNft = 1;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {}
/// ------------------- PUBLIC, VIEW -------------------
function managedTokens(uint256 nft) public view override returns (address[] memory) {
return _managedTokens[nft];
}
function isManagedToken(uint256 nft, address token) public view override returns (bool) {
return _managedTokensIndex[nft][token];
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721, IERC165, AccessControlEnumerable)
returns (bool)
{
return interfaceId == type(ICells).interfaceId || super.supportsInterface(interfaceId);
}
/// ------------------- PUBLIC, MUTATING, GOVERNANCE -------------------
function setPendingPermissionless(bool _pendingPermissionless) external {
require(_isGovernanceOrDelegate(), "PGD");
pendingPermissionless = _pendingPermissionless;
}
function commitPendingPermissionless() external {
require(_isGovernanceOrDelegate(), "PGD");
permissionless = pendingPermissionless;
pendingPermissionless = false;
}
function setPendingMaxTokensPerCell(uint256 _pendingMaxTokensPerCell) external {
require(_isGovernanceOrDelegate(), "PGD");
pendingMaxTokensPerCell = _pendingMaxTokensPerCell;
}
function commitPendingMaxTokensPerCell() external {
require(_isGovernanceOrDelegate(), "PGD");
maxTokensPerCell = pendingMaxTokensPerCell;
pendingMaxTokensPerCell = 0;
}
/// ------------------- PUBLIC, MUTATING, GOVERNANCE OR PERMISSIONLESS -------------------
function createCell(address[] memory cellTokens, bytes memory params) external override returns (uint256) {
require(permissionless || _isGovernanceOrDelegate(), "PGD");
require(cellTokens.length <= maxTokensPerCell, "MT");
require(Array.isSortedAndUnique(cellTokens), "SAU");
uint256 nft = _mintCellNft(cellTokens, params);
_managedTokens[nft] = cellTokens;
for (uint256 i = 0; i < cellTokens.length; i++) {
_managedTokensIndex[nft][cellTokens[i]] = true;
}
emit ICells.CreateCell(_msgSender(), nft, params);
return nft;
}
/// ------------------- PRIVATE, MUTATING -------------------
function _mintCellNft(address[] memory, bytes memory) internal virtual returns (uint256) {
uint256 nft = _topCellNft;
_topCellNft += 1;
_safeMint(_msgSender(), nft);
return nft;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/ITokenCells.sol";
import "./libraries/Array.sol";
import "./libraries/external/LiquidityAmounts.sol";
import "./libraries/external/TickMath.sol";
import "./Cells.sol";
import "./interfaces/external/univ3/IUniswapV3PoolState.sol";
import "./interfaces/external/univ3/IUniswapV3Factory.sol";
import "./interfaces/external/univ3/INonfungiblePositionManager.sol";
contract UniV3Cells is IDelegatedCells, Cells {
using SafeERC20 for IERC20;
INonfungiblePositionManager public immutable positionManager;
mapping(uint256 => uint256) public uniNfts;
constructor(
INonfungiblePositionManager _positionManager,
string memory name,
string memory symbol
) Cells(name, symbol) {
positionManager = _positionManager;
}
/// ------------------- PUBLIC, VIEW -------------------
function delegated(uint256 nft)
public
view
override
returns (address[] memory tokens, uint256[] memory tokenAmounts)
{
uint256 uniNft = uniNfts[nft];
require(uniNft > 0, "UNFT0");
(
,
,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
,
,
,
) = positionManager.positions(uniNft);
IUniswapV3PoolState pool = IUniswapV3PoolState(IUniswapV3Factory(positionManager.factory()).getPool(token0, token1, fee));
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
uint160 sqrtPriceAX96 = TickMath.getSqrtRatioAtTick(tickLower);
uint160 sqrtPriceBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
(uint256 amount0, uint256 amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
sqrtPriceAX96,
sqrtPriceBX96,
liquidity
);
tokenAmounts = new uint256[](2);
tokens = new address[](2);
tokens[0] = token0;
tokens[1] = token1;
tokenAmounts[0] = amount0;
tokenAmounts[1] = amount1;
}
/// ------------------- PUBLIC, MUTATING, NFT_OWNER -------------------
function deposit(
uint256 nft,
address[] calldata tokens,
uint256[] calldata tokenAmounts
) external override returns (uint256[] memory actualTokenAmounts) {
require(_isApprovedOrOwner(_msgSender(), nft), "IO");
require(Array.isSortedAndUnique(tokens), "SAU");
require(tokens.length == tokenAmounts.length, "L");
uint256 uniNft = uniNfts[nft];
require(uniNft > 0, "UNFT0");
(, , address token0, address token1, , , , , , , , ) = positionManager.positions(uniNft);
address[] memory pTokens = new address[](2);
pTokens[0] = token0;
pTokens[1] = token1;
uint256[] memory pTokenAmounts = Array.projectTokenAmounts(pTokens, tokens, tokenAmounts);
for (uint256 i = 0; i < pTokenAmounts.length; i++) {
IERC20(pTokens[i]).safeTransferFrom(_msgSender(), address(this), pTokenAmounts[i]);
_allowTokenIfNecessary(pTokens[i]);
}
(
,
uint256 amount0,
uint256 amount1
) = positionManager.increaseLiquidity(
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: uniNft,
amount0Desired: pTokenAmounts[0],
amount1Desired: pTokenAmounts[1],
// TODO: allow for variable params
amount0Min: 0,
amount1Min: 0,
deadline: block.timestamp + 600
})
);
actualTokenAmounts = new uint256[](2);
actualTokenAmounts[0] = amount0;
actualTokenAmounts[1] = amount1;
for (uint256 i = 0; i < pTokens.length; i++) {
if (actualTokenAmounts[i] < pTokenAmounts[i]) {
IERC20(pTokens[i]).safeTransfer(_msgSender(), pTokenAmounts[i] - actualTokenAmounts[i]);
}
}
emit Deposit(nft, tokens, actualTokenAmounts);
}
function withdraw(
uint256 nft,
address to,
address[] calldata tokens,
uint256[] calldata tokenAmounts
) external override returns (uint256[] memory actualTokenAmounts) {
require(_isApprovedOrOwner(_msgSender(), nft), "IO");
require(Array.isSortedAndUnique(tokens), "SAU");
require(tokens.length == tokenAmounts.length, "L");
uint256 uniNft = uniNfts[nft];
require(uniNft > 0, "UNFT0");
uint256 liquidity = _getWithdrawLiquidity(nft, uniNft, tokens, tokenAmounts);
if (liquidity == 0) {
actualTokenAmounts = new uint256[](2);
actualTokenAmounts[0] = 0;
actualTokenAmounts[1] = 0;
return actualTokenAmounts;
}
(
uint256 amount0,
uint256 amount1
) = positionManager.decreaseLiquidity(
INonfungiblePositionManager.DecreaseLiquidityParams({
tokenId: uniNft,
liquidity: uint128(liquidity),
// TODO: allow for variable params
amount0Min: 0,
amount1Min: 0,
deadline: block.timestamp + 600
})
);
(
uint256 actualAmount0,
uint256 actualAmount1
) = positionManager.collect(INonfungiblePositionManager.CollectParams({
tokenId: uniNft,
recipient: to,
amount0Max: uint128(amount0),
amount1Max: uint128(amount1)
})
);
actualTokenAmounts = new uint256[](2);
actualTokenAmounts[0] = actualAmount0;
actualTokenAmounts[1] = actualAmount1;
emit Withdraw(nft, to, tokens, actualTokenAmounts);
}
/// ------------------- PRIVATE, VIEW -------------------
function _getWithdrawLiquidity(
uint256 nft,
uint256 uniNft,
address[] calldata tokens,
uint256[] calldata tokenAmounts
) internal view returns (uint256) {
(address[] memory pTokens, uint256[] memory totalAmounts) = delegated(nft);
uint256[] memory pTokenAmounts = Array.projectTokenAmounts(pTokens, tokens, tokenAmounts);
(
,
,
,
,
,
,
,
uint128 totalLiquidity,
,
,
,
) = positionManager.positions(uniNft);
if (totalAmounts[0] == 0) {
if (pTokenAmounts[0] == 0) {
return totalLiquidity * pTokenAmounts[1] / totalAmounts[1]; // liquidity1
} else {
return 0;
}
}
if (totalAmounts[1] == 0) {
if (pTokenAmounts[1] == 0) {
return totalLiquidity * pTokenAmounts[0] / totalAmounts[0]; // liquidity0
} else {
return 0;
}
}
uint256 liquidity0 = totalLiquidity * pTokenAmounts[0] / totalAmounts[0];
uint256 liquidity1 = totalLiquidity * pTokenAmounts[1] / totalAmounts[1];
return liquidity0 < liquidity1 ? liquidity0 : liquidity1;
}
/// ------------------- PRIVATE, MUTATING -------------------
function _mintCellNft(address[] memory tokens, bytes memory params) internal virtual override returns (uint256) {
require(params.length == 8 * 32, "IP");
require(tokens.length == 2, "TL");
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
assembly {
fee := mload(add(params, 32))
tickLower := mload(add(params, 64))
tickUpper := mload(add(params, 96))
amount0Desired := mload(add(params, 128))
amount1Desired := mload(add(params, 160))
amount0Min := mload(add(params, 192))
amount1Min := mload(add(params, 224))
deadline := mload(add(params, 256))
}
// !!! Call to untrusted contracts
IERC20(tokens[0]).safeTransferFrom(_msgSender(), address(this), amount0Desired);
IERC20(tokens[1]).safeTransferFrom(_msgSender(), address(this), amount1Desired);
_allowTokenIfNecessary(tokens[0]);
_allowTokenIfNecessary(tokens[1]);
// !!! End call
(uint256 uniNft, , , ) = positionManager.mint(
INonfungiblePositionManager.MintParams({
token0: tokens[0],
token1: tokens[1],
fee: fee,
tickLower: tickLower,
tickUpper: tickUpper,
amount0Desired: amount0Desired,
amount1Desired: amount1Desired,
amount0Min: amount0Min,
amount1Min: amount1Min,
recipient: address(this),
deadline: deadline
})
);
uint256 cellNft = super._mintCellNft(tokens, params);
uniNfts[cellNft] = uniNft;
return cellNft;
}
function _allowTokenIfNecessary(address token) internal {
// Since tokens are not stored at contract address after any tx - it's safe to give unlimited approval
if (IERC20(token).allowance(address(positionManager), address(this)) < type(uint256).max / 2) {
IERC20(token).approve(address(positionManager), type(uint256).max);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
contract GovernanceAccessControl is AccessControlEnumerable {
bytes32 internal constant GOVERNANCE_ROLE = keccak256("governance");
bytes32 internal constant GOVERNANCE_DELEGATE_ROLE = keccak256("governance_delegate");
constructor() {
_setupRole(GOVERNANCE_ROLE, _msgSender());
_setRoleAdmin(GOVERNANCE_ROLE, GOVERNANCE_ROLE);
_setupRole(GOVERNANCE_DELEGATE_ROLE, _msgSender());
_setRoleAdmin(GOVERNANCE_DELEGATE_ROLE, GOVERNANCE_ROLE);
}
function _isGovernanceOrDelegate() internal view returns (bool) {
return hasRole(GOVERNANCE_ROLE, _msgSender()) || hasRole(GOVERNANCE_DELEGATE_ROLE, _msgSender());
}
function _isGovernance() internal view returns (bool) {
return hasRole(GOVERNANCE_ROLE, _msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
interface ICells is IERC721 {
function managedTokens(uint256 nft) external view returns (address[] memory);
function isManagedToken(uint256 nft, address token) external view returns (bool);
function createCell(address[] memory cellTokens, bytes memory params) external returns (uint256);
event CreateCell(address indexed to, uint256 indexed nft, bytes params);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./ICells.sol";
interface IDelegatedCells is ICells {
function delegated(uint256 nft) external view returns (address[] memory tokens, uint256[] memory tokenAmounts);
function deposit(
uint256 nft,
address[] calldata tokens,
uint256[] calldata tokenAmounts
) external returns (uint256[] memory actualTokenAmounts);
function withdraw(
uint256 nft,
address to,
address[] calldata tokens,
uint256[] calldata tokenAmounts
) external returns (uint256[] memory actualTokenAmounts);
event Deposit(
uint256 nft,
address[] tokens,
uint256[] actualTokenAmounts
);
event Withdraw(
uint256 nft,
address to,
address[] tokens,
uint256[] actualTokenAmounts
);
// TODO: add methods for collecting liquidity mining rewards
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./IDelegatedCells.sol";
interface ITokenCells is IDelegatedCells {
function claimTokensToCell(
uint256 nft,
address[] calldata tokens,
uint256[] calldata tokenAmounts
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
// TODO: Check the license
pragma solidity 0.8.7;
pragma abicoder v2;
import "./IPeripheryImmutableState.sol";
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is IPeripheryImmutableState {
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
// TODO: Check the license
pragma solidity =0.8.7;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// TODO: Check the license
pragma solidity =0.8.7;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The pool address
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
// TODO: Check the license
pragma solidity =0.8.7;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
library Array {
function bubbleSort(address[] memory arr) internal pure {
uint256 l = arr.length;
for (uint256 i = 0; i < l; i++) {
for (uint256 j = i + 1; j < l; j++) {
if (arr[i] > arr[j]) {
address temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
function isSortedAndUnique(address[] memory tokens) internal pure returns (bool) {
if (tokens.length < 2) {
return true;
}
for (uint256 i = 0; i < tokens.length - 1; i++) {
if (tokens[i] >= tokens[i + 1]) {
return false;
}
}
return true;
}
/// @dev
/// Requires both sets of tokens to be sorted. When tokens are not sorted, it's undefined behavior.
/// If there is a token in tokensToProject that is not part of tokens and corresponding tokenAmountsToProject > 0, reverts.
/// Zero token amount is eqiuvalent to missing token
function projectTokenAmounts(
address[] memory tokens,
address[] memory tokensToProject,
uint256[] memory tokenAmountsToProject
) internal pure returns (uint256[] memory) {
uint256[] memory res = new uint256[](tokens.length);
uint256 t = 0;
uint256 tp = 0;
while ((t < tokens.length) && (tp < tokensToProject.length)) {
if (tokens[t] < tokensToProject[tp]) {
res[t] = 0;
t++;
} else if (tokens[t] > tokensToProject[tp]) {
if (tokenAmountsToProject[tp] == 0) {
tp++;
} else {
revert("TPS");
}
} else {
res[t] = tokenAmountsToProject[tp];
t++;
tp++;
}
}
while (t < tokens.length) {
res[t] = 0;
t++;
}
return res;
}
/// @notice Splits each amount from `amounts` into k amounts according to `weights`.
/// @dev Requires tokens and tokenAmounts to be vector of size n and delegatedTokenAmounts to be k x n matrix
/// so that delegatedTokenAmounts[i] is a vector of size n
/// norm is a vector 1 x k
/// the error is up to k tokens due to rounding
/// @param amounts Amounts to split, vector n x 1
/// @param weights Weights of the split, matrix n x k, weights[i] is vector n x 1.
/// Weights do not need to sum to 1 in each column, but they will be normalized on split.
function splitAmounts(uint256[] memory amounts, uint256[][] memory weights)
internal
pure
returns (uint256[][] memory)
{
uint256 k = weights.length;
require(k > 0, "KGT0");
uint256 n = amounts.length;
require(n > 0, "NGT0");
uint256[] memory weightsNorm = new uint256[](n);
for (uint256 i = 0; i < k; i++) {
require(weights[i].length == n, "NV");
}
for (uint256 j = 0; j < n; j++) {
weightsNorm[j] = 0;
for (uint256 i = 0; i < k; i++) {
weightsNorm[j] += weights[i][j];
}
}
uint256[][] memory res = new uint256[][](k);
for (uint256 i = 0; i < k; i++) {
res[i] = new uint256[](n);
for (uint256 j = 0; j < n; j++) {
res[i][j] = (weights[i][j] * amounts[j]) / weightsNorm[j];
}
}
return res;
}
function _isSubsetOf(
address[] memory tokens,
address[] memory tokensToCheck,
address[] memory amountsToCheck
) internal {}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.7;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.7;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(aรbรทdenominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// diff: original lib works under 0.7.6 with overflows enabled
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
// diff: original uint256 twos = -denominator & denominator;
uint256 twos = uint256(-int256(denominator)) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(aรbรทdenominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// diff: original lib works under 0.7.6 with overflows enabled
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.7;
import "./FullMath.sol";
import "./FixedPoint96.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.7;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
// diff: original require(absTick <= uint256(MAX_TICK), "T");
require(absTick <= uint256(int256(MAX_TICK)), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
|
Since tokens are not stored at contract address after any tx - it's safe to give unlimited approval
|
function _allowTokenIfNecessary(address token) internal {
if (IERC20(token).allowance(address(positionManager), address(this)) < type(uint256).max / 2) {
IERC20(token).approve(address(positionManager), type(uint256).max);
}
}
| 6,996,309
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.18;
pragma experimental ABIEncoderV2;
/// @title Data zipping functions
/// @author Giovanni Rescinito
/// @notice implements the zipping operations used to compress lists of values in a single data location
library Zipper {
/// @notice checks that the width proposed is compatible with the zipping operations
/// @param width the value to check
modifier checkWidth(uint width){
require((width == 4) || (width == 8) || (width == 16) || (width == 32) || (width == 64) || (width == 128),
"Width unsupported");
_;
}
/// @notice zips an array of values to a single data location
/// @param array the array to zip
/// @param width the number of bits used for each value
/// @return the zipped version of the array
function zip(uint[] memory array, uint width) pure private returns (uint){
uint zipped = 0;
uint size = array.length;
if (size == 0){
return zipped;
}
for (uint i=size;i>1;i--){
require(array[i-1] < (2**width), "Value exceeding 2^width");
zipped += array[i-1];
zipped = zipped << width;
}
require(array[0] < (2**width), "Value exceeding 2^width");
zipped += array[0];
return zipped;
}
/// @notice unzips a zipped value to the corresponding array of values
/// @param zipped the zipped value
/// @param width the number of bits used for each value
/// @param size the number of values to extract
/// @return the array of the unzipped values
function unzip(uint zipped, uint width, uint size) pure private returns (uint[] memory){
uint[] memory array = new uint[](size);
for (uint i=0;i<size;i++){
array[i] = zipped % (2**width);
zipped = zipped >> width;
}
return array;
}
/// @notice zips an array of values using two different widths in an alternate manner
/// @param array the values to zip
/// @param w1 the first width to use
/// @param w2 the second width to use
/// @return the zipped version of the array
function zipDouble(uint[] memory array, uint w1, uint w2) pure private returns (uint){
uint zipped = 0;
uint size = array.length;
if (size == 0){
return zipped;
}
for (uint i=size;i>2;i-=2){
require(array[i-1] < (2**w2), "Value exceeding 2^w2");
zipped += array[i-1];
zipped = zipped << w1;
require(array[i-2] < (2**w1), "Value exceeding 2^w1");
zipped += array[i-2];
zipped = zipped << w2;
}
require(array[1] < (2**w2), "Value exceeding 2^w2");
zipped += array[1];
zipped = zipped << w1;
require(array[0] < (2**w1), "Value exceeding 2^w1");
zipped += array[0];
return zipped;
}
/// @notice unzips a value zipped with two different widths to the corresponding array of values
/// @param zipped the zipped value
/// @param w1 the first width to use
/// @param w2 the second width to use
/// @param size the number of values to extract
/// @return the array of the unzipped values
function unzipDouble(uint zipped, uint w1, uint w2, uint size) pure private returns (uint[] memory){
uint[] memory array = new uint[](size);
for (uint i=0;i<size;i+=2){
array[i] = zipped % (2**w1);
zipped = zipped >> w1;
array[i+1] = zipped % (2**w2);
zipped = zipped >> w2;
}
return array;
}
/// @notice zips an array of values using two different widths in an alternate manner and includes the size at the end
/// @param array the values to zip
/// @return the zipped version of the array
function zipDoubleArrayWithSize(uint[] memory array) pure public returns (uint){
uint size = array.length;
require((size/2)<=(256/32 - 1), "Too many values");
uint zipped = zipDouble(array,8,24);
zipped = zipped << 32;
zipped += size;
return zipped;
}
/// @notice unzips a value, after extracting the size, to the corresponding array of values zipped with two different widths
/// @param zipped the zipped value
/// @return the array of the unzipped values
function unzipDoubleArrayWithSize(uint zipped) pure public returns (uint[] memory){
uint size = zipped % (2**32);
zipped = zipped >> 32;
return unzipDouble(zipped, 8, 24, size);
}
/// @notice zips an array of values using two different widths in an alternate manner, including the size at the end
/// @param array the values to zip
/// @param width the number of bits used for each value
/// @return the zipped version of the array
function zipArrayWithSize(uint[] memory array, uint width) pure public checkWidth(width) returns (uint){
uint size = array.length;
require(size<=(256/width - 1), "Too many values");
uint zipped = zip(array,width);
zipped = zipped << width;
zipped += size;
return zipped;
}
/// @notice unzips a value, after extracting the size, to the corresponding array of values
/// @param zipped the zipped value
/// @param width the number of bits used for each value
/// @return the array of the unzipped values
function unzipArrayWithSize(uint zipped, uint width) pure public checkWidth(width) returns (uint[] memory){
uint size = zipped % (2**width);
zipped = zipped >> width;
return unzip(zipped,width,size);
}
/// @notice zips an arbitrary length array of values
/// @param array the values to zip
/// @param width the number of bits used for each value
/// @return an array containing all the zipped values required to zip the starting array
function zipArray(uint[] memory array, uint width) pure public checkWidth(width) returns (uint[] memory){
uint n = 256/width;
uint cols = array.length;
uint size = cols/n;
uint last_size = cols%n;
uint[] memory zipped = new uint[](size+1);
uint[] memory tmp;
uint x;
for (uint j=0;j<size;j++){
tmp = new uint[](n);
x = 0;
for (uint k=j*n;k<(j+1)*n;k++){
tmp[x] = array[k];
x++;
}
zipped[j] = zip(tmp,width);
}
tmp = new uint[](last_size);
x = 0;
for (uint k=size*n;k<cols;k++){
tmp[x] = array[k];
x++;
}
zipped[size] = zipArrayWithSize(tmp,width);
return zipped;
}
/// @notice unzips an array of zipped values
/// @param array the values to unzip
/// @param width the number of bits used for each value
/// @return an array containing all the values obtained after unzipping each of the values of the provided array
function unzipArray(uint[] memory array, uint width)pure public checkWidth(width) returns (uint[] memory){
uint size = array.length;
if (size == 0){
return new uint[](0);
}
uint n = 256/width;
uint index;
uint[] memory last = unzipArrayWithSize(array[size-1],width);
uint[] memory unzipped = new uint[](n*(size-1) + last.length);
for (uint i=0;i<size-1;i++){
uint[] memory tmp = unzip(array[i],width,n);
index = i*n;
for (uint j=0;j<n;j++){
unzipped[index] = tmp[j];
index++;
}
}
index = n*(size-1);
for (uint i=0;i<last.length;i++){
unzipped[index] = last[i];
index++;
}
return unzipped;
}
/// @notice zips a matrix of values, row by row
/// @param matrix the matrix of values to zip
/// @param width the number of bits used for each value
/// @return a zipped matrix, where each row is a zipped array containing all the values of that row zipped
function zipMatrix(uint[][] memory matrix, uint width) pure public checkWidth(width) returns (uint[][] memory){
uint rows = matrix.length;
uint[][] memory zipped = new uint[][](rows);
for (uint i=0;i<rows;i++){
zipped[i] = zipArray(matrix[i],width);
}
return zipped;
}
/// @notice unzips a matrix of values, row by row
/// @param matrix the matrix of values to unzip
/// @param width the number of bits used for each value
/// @return a matrix, where each row contains all the values obtained after unzipping that row
function unzipMatrix(uint[][] memory matrix, uint width)pure public checkWidth(width) returns (uint[][] memory){
uint rows = matrix.length;
uint[][] memory unzipped = new uint[][](rows);
for (uint i=0;i<rows;i++){
unzipped[i] = unzipArray(matrix[i],width);
}
return unzipped;
}
/// @notice zips two array of values using two different widths and combines them into a single array in an alternate manner
/// @param a1 the first array to zip
/// @param a2 the second array to zip
/// @return the zipped version of the two arrays
function zipDoubleArray(uint[] memory a1, uint[] memory a2) pure public returns (uint[] memory){
require(a1.length == a2.length, "Different array sizes");
uint n = 256/32;
uint cols = a1.length;
uint size = cols/n;
uint last_size = cols%n;
uint[] memory zipped = new uint[](size+1);
uint[] memory tmp;
uint x;
for (uint j=0;j<size;j++){
tmp = new uint[](2*n);
x = 0;
for (uint k=j*n;k<(j+1)*n;k++){
tmp[x++] = a1[k];
tmp[x++] = a2[k];
}
zipped[j] = zipDouble(tmp, 8, 24);
}
tmp = new uint[](2*last_size);
x = 0;
for (uint k=size*n;k<cols;k++){
tmp[x++] = a1[k];
tmp[x++] = a2[k];
}
zipped[size] = zipDoubleArrayWithSize(tmp);
return zipped;
}
/// @notice unzips an array of values using two different widths in an alternate manner
/// @param array the array to unzip
/// @return the values obtained after unzipping the array
function unzipDoubleArray(uint[] memory array)pure public returns (uint[] memory){
uint size = array.length;
if (size == 0){
return new uint[](0);
}
uint n = 256/32*2;
uint index;
uint[] memory last = unzipDoubleArrayWithSize(array[size-1]);
uint[] memory unzipped = new uint[](n*(size-1) + last.length);
for (uint i=0;i<size-1;i++){
uint[] memory tmp = unzipDouble(array[i],8,24,n);
index = i*n;
for (uint j=0;j<n;j++){
unzipped[index] = tmp[j];
index++;
}
}
index = n*(size-1);
for (uint i=0;i<last.length;i++){
unzipped[index] = last[i];
index++;
}
return unzipped;
}
/// @notice unzips a matrix of values using two different widths in an alternate manner
/// @param matrix the matrix to unzip
/// @return the unzipped matrix, where each row is the unzipped version of the corresponding row, obtained after unzipping using two different widths
function unzipDoubleMatrix(uint[][] memory matrix)pure private returns (uint[][] memory){
uint rows = matrix.length;
uint[][] memory unzipped = new uint[][](rows);
for (uint i=0;i<rows;i++){
unzipped[i] = unzipDoubleArray(matrix[i]);
}
return unzipped;
}
/// @notice unzips the zipped score matrix and reconstructs the nxn starting matrix
/// @param scoreMat the zipped score matrix
/// @return the unzipped nxn score matrix
function reconstructScoreMatrix(uint[][] memory scoreMat) pure public returns (uint[][] memory){
uint[][] memory scores = unzipDoubleMatrix(scoreMat);
uint n = scores.length;
uint[][] memory scoreMatrix = new uint[][](n);
for (uint i=0;i<n;i++){
scoreMatrix[i] = new uint[](n);
uint len = scores[i].length;
for (uint j=0;j<len;j+=2){
scoreMatrix[i][scores[i][j]] = scores[i][j+1];
}
}
return scoreMatrix;
}
}
|
zips an array of values using two different widths in an alternate manner, including the size at the end array the values to zip width the number of bits used for each value return the zipped version of the array
|
function zipArrayWithSize(uint[] memory array, uint width) pure public checkWidth(width) returns (uint){
uint size = array.length;
require(size<=(256/width - 1), "Too many values");
uint zipped = zip(array,width);
zipped = zipped << width;
zipped += size;
return zipped;
}
| 14,058,667
|
pragma solidity ^0.4.18;
contract owned {
/* Owner definition. */
address public owner; // Owner address.
function owned() internal {
owner = msg.sender ;
}
modifier onlyOwner {
require(msg.sender == owner); _;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract token {
/* Base token definition. */
string public name; // Name for the token.
string public symbol; // Symbol for the token.
uint8 public decimals; // Number of decimals of the token.
uint256 public totalSupply; // Total of tokens created.
// Array containing the balance foreach address.
mapping (address => uint256) public balanceOf;
// Array containing foreach address, an array containing each approved address and the amount of tokens it can spend.
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify about a transfer done. */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes the contract */
function token(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) internal {
balanceOf[msg.sender] = initialSupply; // Gives the creator all initial tokens.
totalSupply = initialSupply; // Update total supply.
name = tokenName; // Set the name for display purposes.
symbol = tokenSymbol; // Set the symbol for display purposes.
decimals = decimalUnits; // Amount of decimals for display purposes.
}
/* 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.
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.
Transfer(_from, _to, _value); // Notifies the blockchain about the transfer.
}
/// @notice 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);
}
/// @notice Send `_value` tokens to `_to` in behalf of `_from`.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _value The amount to send.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance.
allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent.
_transfer(_from, _to, _value); // Makes the transfer.
return true;
}
/// @notice Allows `_spender` to spend a maximum of `_value` tokens in your behalf.
/// @param _spender The address authorized to spend.
/// @param _value The max amount they can spend.
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value; // Adds a new register to allowance, permiting _spender to use _value of your tokens.
return true;
}
}
contract PMHToken is owned, token {
/* Specific token definition for -HormitechToken-. */
uint256 public sellPrice = 5000000000000000; // Price applied if someone wants to sell a token.
uint256 public buyPrice = 10000000000000000; // Price applied if someone wants to buy a token.
bool public closeBuy = false; // If true, nobody will be able to buy.
bool public closeSell = false; // If true, nobody will be able to sell.
uint256 public tokensAvailable = balanceOf[this]; // Number of tokens available for sell.
uint256 public solvency = this.balance; // Amount of Ether available to pay sales.
uint256 public profit = 0; // Shows the actual profit for the company.
address public comisionGetter = 0x70B593f89DaCF6e3BD3e5bD867113FEF0B2ee7aD ; // The address that gets the comisions paid.
// added MAR 2018
mapping (address => string ) public emails ; // Array containing the e-mail addresses of the token holders
mapping (uint => uint) public dividends ; // for each period in the index, how many weis set for dividends distribution
mapping (address => uint[]) public paidDividends ; // for each address, if the period dividend was paid or not and the amount
// added MAR 2018
mapping (address => bool) public frozenAccount; // Array containing foreach address if it's frozen or not.
/* This generates a public event on the blockchain that will notify about an address being freezed. */
event FrozenFunds(address target, bool frozen);
/* This generates a public event on the blockchain that will notify about an addition of Ether to the contract. */
event LogDeposit(address sender, uint amount);
/* This generates a public event on the blockchain that will notify about a Withdrawal of Ether from the contract. */
event LogWithdrawal(address receiver, uint amount);
/* Initializes the contract */
function PMHToken(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) public
token (initialSupply, tokenName, decimalUnits, tokenSymbol) {}
/* 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.
require(balanceOf[_from] >= _value); // Check if the sender has enough.
require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows.
require(!frozenAccount[_from]); // Check if sender is frozen.
require(!frozenAccount[_to]); // Check if recipient is frozen.
balanceOf[_from] -= _value; // Subtracts _value tokens from the sender.
balanceOf[_to] += _value; // Adds the same amount to the recipient.
_updateTokensAvailable(balanceOf[this]); // Update the balance of tokens available if necessary.
Transfer(_from, _to, _value); // Notifies the blockchain about the transfer.
}
function refillTokens(uint256 _value) public onlyOwner{
// Owner sends tokens to the contract.
_transfer(msg.sender, this, _value);
}
/* Overrides basic transfer function due to comision value */
function transfer(address _to, uint256 _value) public {
// This function requires a comision value of 0.4% of the market value.
uint market_value = _value * sellPrice;
uint comision = market_value * 4 / 1000;
// The token smart-contract pays comision, else the transfer is not possible.
require(this.balance >= comision);
comisionGetter.transfer(comision); // Transfers comision to the comisionGetter.
_transfer(msg.sender, _to, _value);
}
/* Overrides basic transferFrom function due to comision value */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance.
// This function requires a comision value of 0.4% of the market value.
uint market_value = _value * sellPrice;
uint comision = market_value * 4 / 1000;
// The token smart-contract pays comision, else the transfer is not possible.
require(this.balance >= comision);
comisionGetter.transfer(comision); // Transfers comision to the comisionGetter.
allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent.
_transfer(_from, _to, _value); // Makes the transfer.
return true;
}
/* Internal, updates the balance of tokens available. */
function _updateTokensAvailable(uint256 _tokensAvailable) internal { tokensAvailable = _tokensAvailable; }
/* Internal, updates the balance of Ether available in order to cover potential sales. */
function _updateSolvency(uint256 _solvency) internal { solvency = _solvency; }
/* Internal, updates the profit value */
function _updateProfit(uint256 _increment, bool add) internal{
if (add){
// Increase the profit value
profit = profit + _increment;
}else{
// Decrease the profit value
if(_increment > profit){ profit = 0; }
else{ profit = profit - _increment; }
}
}
/// @notice Create `mintedAmount` tokens and send it to `target`.
/// @param target Address to receive the tokens.
/// @param mintedAmount The amount of tokens target will receive.
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount; // Updates target's balance.
totalSupply += mintedAmount; // Updates totalSupply.
_updateTokensAvailable(balanceOf[this]); // Update the balance of tokens available if necessary.
Transfer(0, this, mintedAmount); // Notifies the blockchain about the tokens created.
Transfer(this, target, mintedAmount); // Notifies the blockchain about the transfer to target.
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens.
/// @param target Address to be frozen.
/// @param freeze Either to freeze target or not.
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze; // Sets the target status. True if it's frozen, False if it's not.
FrozenFunds(target, freeze); // Notifies the blockchain about the change of state.
}
/// @notice Allow addresses to pay `newBuyPrice`ETH when buying and receive `newSellPrice`ETH when selling, foreach token bought/sold.
/// @param newSellPrice Price applied when an address sells its tokens, amount in WEI (1ETH = 10ยนโธWEI).
/// @param newBuyPrice Price applied when an address buys tokens, amount in WEI (1ETH = 10ยนโธWEI).
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice; // Updates the buying price.
buyPrice = newBuyPrice; // Updates the selling price.
}
/// @notice Sets the state of buy and sell operations
/// @param isClosedBuy True if buy operations are closed, False if opened.
/// @param isClosedSell True if sell operations are closed, False if opened.
function setStatus(bool isClosedBuy, bool isClosedSell) onlyOwner public {
closeBuy = isClosedBuy; // Updates the state of buy operations.
closeSell = isClosedSell; // Updates the state of sell operations.
}
/// @notice Deposits Ether to the contract
function deposit() payable public returns(bool success) {
require((this.balance + msg.value) > this.balance); // Checks for overflows.
//Contract has already received the Ether when this function is executed.
_updateSolvency(this.balance); // Updates the solvency value of the contract.
_updateProfit(msg.value, false); // Decrease profit value.
// Decrease because deposits will be done mostly by the owner.
// Possible donations won't count as profit for the company, but in favor of the investors.
LogDeposit(msg.sender, msg.value); // Notifies the blockchain about the Ether received.
return true;
}
/// @notice The owner withdraws Ether from the contract.
/// @param amountInWeis Amount of ETH in WEI which will be withdrawed.
function withdraw(uint amountInWeis) onlyOwner public {
LogWithdrawal(msg.sender, amountInWeis); // Notifies the blockchain about the withdrawal.
_updateSolvency( (this.balance - amountInWeis) ); // Updates the solvency value of the contract.
_updateProfit(amountInWeis, true); // Increase the profit value.
owner.transfer(amountInWeis); // Sends the Ether to owner address.
}
function withdrawDividends(uint amountInWeis) internal returns(bool success) {
LogWithdrawal(msg.sender, amountInWeis); // Notifies the blockchain about the withdrawal.
_updateSolvency( (this.balance - amountInWeis) ); // Updates the solvency value of the contract.
msg.sender.transfer(amountInWeis); // Sends the Ether to owner address.
return true ;
}
/// @notice Buy tokens from contract by sending Ether.
function buy() public payable {
require(!closeBuy); //Buy operations must be opened
uint amount = msg.value / buyPrice; //Calculates the amount of tokens to be sent
uint market_value = amount * buyPrice; //Market value for this amount
uint comision = market_value * 4 / 1000; //Calculates the comision for this transaction
uint profit_in_transaction = market_value - (amount * sellPrice) - comision; //Calculates the relative profit for this transaction
require(this.balance >= comision); //The token smart-contract pays comision, else the operation is not possible.
comisionGetter.transfer(comision); //Transfers comision to the comisionGetter.
_transfer(this, msg.sender, amount); //Makes the transfer of tokens.
_updateSolvency((this.balance - profit_in_transaction)); //Updates the solvency value of the contract.
_updateProfit(profit_in_transaction, true); //Increase the profit value.
owner.transfer(profit_in_transaction); //Sends profit to the owner of the contract.
}
/// @notice Sell `amount` tokens to the contract.
/// @param amount amount of tokens to be sold.
function sell(uint256 amount) public {
require(!closeSell); //Sell operations must be opened
uint market_value = amount * sellPrice; //Market value for this amount
uint comision = market_value * 4 / 1000; //Calculates the comision for this transaction
uint amount_weis = market_value + comision; //Total in weis that must be paid
require(this.balance >= amount_weis); //Contract must have enough weis
comisionGetter.transfer(comision); //Transfers comision to the comisionGetter
_transfer(msg.sender, this, amount); //Makes the transfer of tokens, the contract receives the tokens.
_updateSolvency( (this.balance - amount_weis) ); //Updates the solvency value of the contract.
msg.sender.transfer(market_value); //Sends Ether to the seller.
}
/// Default function, sender buys tokens by sending ether to the contract:
function () public payable { buy(); }
function setDividends(uint _period, uint _totalAmount) onlyOwner public returns (bool success) {
require(this.balance >= _totalAmount ) ;
// period is 201801 201802 etc. yyyymm - no more than 1 dividend distribution per month
dividends[_period] = _totalAmount ;
return true ;
}
function setEmail(string _email ) public returns (bool success) {
require(balanceOf[msg.sender] > 0 ) ;
// require(emails[msg.sender] == "" ) ; // checks the e-mail for this address was not already set
emails[msg.sender] = _email ;
return true ;
}
function dividendsGetPaid(uint _period) public returns (bool success) {
uint percentageDividends ;
uint qtyDividends ;
require(!frozenAccount[msg.sender]); // frozen accounts are not allowed to withdraw ether
require(balanceOf[msg.sender] > 0 ) ; // sender has a positive balance of tokens to get paid
require(dividends[_period] > 0) ; // there is an active dividend period
require(paidDividends[msg.sender][_period] == 0) ; // the dividend for this token holder was not yet paid
// using here a 10000 (ten thousand) arbitrary multiplying factor for floating point precision
percentageDividends = (balanceOf[msg.sender] / totalSupply ) * 10000 ;
qtyDividends = ( percentageDividends * dividends[_period] ) / 10000 ;
require(this.balance >= qtyDividends) ; // contract has enough ether to pay this dividend
paidDividends[msg.sender][_period] = qtyDividends ; // record the dividend was paid
require(withdrawDividends(qtyDividends));
return true ;
}
function adminResetEmail(address _address, string _newEmail ) public onlyOwner {
require(balanceOf[_address] > 0 ) ;
emails[_address] = _newEmail ;
}
}
|
Buy tokens from contract by sending Ether.
|
function buy() public payable {
}
| 12,123,734
|
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IFactory} from "../factory/IFactory.sol";
import {IInstanceRegistry} from "../factory/InstanceRegistry.sol";
import {ProxyFactory} from "../factory/ProxyFactory.sol";
import {IUniversalVault} from "./Visor.sol";
/// @title VisorFactory
contract VisorFactory is Ownable, IFactory, IInstanceRegistry, ERC721 {
bytes32[] public names;
mapping(bytes32=>address) public templates;
bytes32 public activeTemplate;
mapping(address=>address[]) public userIndex;
event TemplateAdded(bytes32 indexed name, address indexed template);
event TemplateActive(bytes32 indexed name, address indexed template);
constructor() ERC721("VISOR", "VISOR") {}
function addTemplate(bytes32 name, address template) public onlyOwner {
require(templates[name] == address(0), "Template already exists");
templates[name] = template;
if(names.length == 0) {
activeTemplate = name;
emit TemplateActive(name, template);
}
names.push(name);
emit TemplateAdded(name, template);
}
function setActive(bytes32 name) public onlyOwner {
require(templates[name] != address(0), "Template does not exist");
activeTemplate = name;
emit TemplateActive(name, templates[name]);
}
/* registry functions */
function isInstance(address instance) external view override returns (bool validity) {
return ERC721._exists(uint256(instance));
}
function instanceCount() external view override returns (uint256 count) {
return ERC721.totalSupply();
}
function instanceAt(uint256 index) external view override returns (address instance) {
return address(ERC721.tokenByIndex(index));
}
/* factory functions */
function createSelected(bytes32 name) public returns (address vault) {
// create clone and initialize
vault = ProxyFactory._create(
templates[name],
abi.encodeWithSelector(IUniversalVault.initialize.selector)
);
// mint nft to caller
ERC721._safeMint(msg.sender, uint256(vault));
userIndex[msg.sender].push(vault);
// emit event
emit InstanceAdded(vault);
// explicit return
return vault;
}
function createSelected2(bytes32 name, bytes32 salt) public returns (address vault) {
// create clone and initialize
vault = ProxyFactory._create2(
templates[name],
abi.encodeWithSelector(IUniversalVault.initialize.selector),
salt
);
// mint nft to caller
ERC721._safeMint(msg.sender, uint256(vault));
userIndex[msg.sender].push(vault);
// emit event
emit InstanceAdded(vault);
// explicit return
return vault;
}
function create(bytes calldata) external override returns (address vault) {
return create();
}
function create2(bytes calldata, bytes32 salt) external override returns (address vault) {
return create2(salt);
}
function create() public returns (address vault) {
// create clone and initialize
vault = ProxyFactory._create(
templates[activeTemplate],
abi.encodeWithSelector(IUniversalVault.initialize.selector)
);
// mint nft to caller
ERC721._safeMint(msg.sender, uint256(vault));
userIndex[msg.sender].push(vault);
// emit event
emit InstanceAdded(vault);
// explicit return
return vault;
}
function create2(bytes32 salt) public returns (address vault) {
// create clone and initialize
vault = ProxyFactory._create2(
templates[activeTemplate],
abi.encodeWithSelector(IUniversalVault.initialize.selector),
salt
);
// mint nft to caller
ERC721._safeMint(msg.sender, uint256(vault));
userIndex[msg.sender].push(vault);
// emit event
emit InstanceAdded(vault);
// explicit return
return vault;
}
/* getter functions */
function nameCount() public view returns(uint256) {
return names.length;
}
function vaultCount(address user) public view returns(uint256) {
return userIndex[user].length;
}
function getUserVault(address user, uint256 index) public view returns (address) {
return userIndex[user][index];
}
function getTemplate() external view returns (address) {
return templates[activeTemplate];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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_) {
_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.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: GPL-3.0-only
pragma solidity 0.7.6;
interface IFactory {
function create(bytes calldata args) external returns (address instance);
function create2(bytes calldata args, bytes32 salt) external returns (address instance);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
interface IInstanceRegistry {
/* events */
event InstanceAdded(address instance);
event InstanceRemoved(address instance);
/* view functions */
function isInstance(address instance) external view returns (bool validity);
function instanceCount() external view returns (uint256 count);
function instanceAt(uint256 index) external view returns (address instance);
}
/// @title InstanceRegistry
contract InstanceRegistry is IInstanceRegistry {
using EnumerableSet for EnumerableSet.AddressSet;
/* storage */
EnumerableSet.AddressSet private _instanceSet;
/* view functions */
function isInstance(address instance) external view override returns (bool validity) {
return _instanceSet.contains(instance);
}
function instanceCount() external view override returns (uint256 count) {
return _instanceSet.length();
}
function instanceAt(uint256 index) external view override returns (address instance) {
return _instanceSet.at(index);
}
/* admin functions */
function _register(address instance) internal {
require(_instanceSet.add(instance), "InstanceRegistry: already registered");
emit InstanceAdded(instance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
library ProxyFactory {
/* functions */
function _create(address logic, bytes memory data) internal returns (address proxy) {
// deploy clone
proxy = Clones.clone(logic);
// attempt initialization
if (data.length > 0) {
(bool success, bytes memory err) = proxy.call(data);
require(success, string(err));
}
// explicit return
return proxy;
}
function _create2(
address logic,
bytes memory data,
bytes32 salt
) internal returns (address proxy) {
// deploy clone
proxy = Clones.cloneDeterministic(logic, salt);
// attempt initialization
if (data.length > 0) {
(bool success, bytes memory err) = proxy.call(data);
require(success, string(err));
}
// explicit return
return proxy;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {EIP712} from "./EIP712.sol";
import {ERC1271} from "./ERC1271.sol";
import {OwnableERC721} from "./OwnableERC721.sol";
import {IRageQuit} from "../hypervisor/Hypervisor.sol";
interface IUniversalVault {
/* user events */
event Locked(address delegate, address token, uint256 amount);
event Unlocked(address delegate, address token, uint256 amount);
event RageQuit(address delegate, address token, bool notified, string reason);
/* data types */
struct LockData {
address delegate;
address token;
uint256 balance;
}
/* initialize function */
function initialize() external;
/* user functions */
function lock(
address token,
uint256 amount,
bytes calldata permission
) external;
function unlock(
address token,
uint256 amount,
bytes calldata permission
) external;
function rageQuit(address delegate, address token)
external
returns (bool notified, string memory error);
function transferERC20(
address token,
address to,
uint256 amount
) external;
function transferETH(address to, uint256 amount) external payable;
/* pure functions */
function calculateLockID(address delegate, address token)
external
pure
returns (bytes32 lockID);
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) external view returns (bytes32 permissionHash);
function getNonce() external view returns (uint256 nonce);
function owner() external view returns (address ownerAddress);
function getLockSetCount() external view returns (uint256 count);
function getLockAt(uint256 index) external view returns (LockData memory lockData);
function getBalanceDelegated(address token, address delegate)
external
view
returns (uint256 balance);
function getBalanceLocked(address token) external view returns (uint256 balance);
function checkBalances() external view returns (bool validity);
}
/// @title Visor
/// @notice Vault for isolated storage of staking tokens
/// @dev Warning: not compatible with rebasing tokens
contract Visor is
IUniversalVault,
EIP712("UniversalVault", "1.0.0"),
ERC1271,
OwnableERC721,
Initializable
{
using SafeMath for uint256;
using Address for address;
using Address for address payable;
using EnumerableSet for EnumerableSet.Bytes32Set;
/* constant */
// Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks
// the gas requirement cannot be determined at runtime by querying the delegate
// as it could potentially be manipulated by a malicious delegate who could force
// the calls to revert.
// The gas limit could alternatively be set upon vault initialization or creation
// of a lock, but the gas consumption trade-offs are not favorable.
// Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public constant RAGEQUIT_GAS = 500000;
bytes32 public constant LOCK_TYPEHASH =
keccak256("Lock(address delegate,address token,uint256 amount,uint256 nonce)");
bytes32 public constant UNLOCK_TYPEHASH =
keccak256("Unlock(address delegate,address token,uint256 amount,uint256 nonce)");
string public constant VERSION = "VISOR-1.0.0";
/* storage */
uint256 private _nonce;
mapping(bytes32 => LockData) private _locks;
EnumerableSet.Bytes32Set private _lockSet;
/* initialization function */
function initializeLock() external initializer {}
function initialize() external override initializer {
OwnableERC721._setNFT(msg.sender);
}
/* ether receive */
receive() external payable {}
/* internal overrides */
function _getOwner() internal view override(ERC1271) returns (address ownerAddress) {
return OwnableERC721.owner();
}
/* pure functions */
function calculateLockID(address delegate, address token)
public
pure
override
returns (bytes32 lockID)
{
return keccak256(abi.encodePacked(delegate, token));
}
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) public view override returns (bytes32 permissionHash) {
return
EIP712._hashTypedDataV4(
keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce))
);
}
function getNonce() external view override returns (uint256 nonce) {
return _nonce;
}
function owner()
public
view
override(IUniversalVault, OwnableERC721)
returns (address ownerAddress)
{
return OwnableERC721.owner();
}
function getLockSetCount() external view override returns (uint256 count) {
return _lockSet.length();
}
function getLockAt(uint256 index) external view override returns (LockData memory lockData) {
return _locks[_lockSet.at(index)];
}
function getBalanceDelegated(address token, address delegate)
external
view
override
returns (uint256 balance)
{
return _locks[calculateLockID(delegate, token)].balance;
}
function getBalanceLocked(address token) public view override returns (uint256 balance) {
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
LockData storage _lockData = _locks[_lockSet.at(index)];
if (_lockData.token == token && _lockData.balance > balance)
balance = _lockData.balance;
}
return balance;
}
function checkBalances() external view override returns (bool validity) {
// iterate over all token locks and validate sufficient balance
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
// fetch storage lock reference
LockData storage _lockData = _locks[_lockSet.at(index)];
// if insufficient balance and noโt shutdown, return false
if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false;
}
// if sufficient balance or shutdown, return true
return true;
}
/* user functions */
/// @notice Lock ERC20 tokens in the vault
/// access control: called by delegate with signed permission from owner
/// state machine: anytime
/// state scope:
/// - insert or update _locks
/// - increase _nonce
/// token transfer: none
/// @param token Address of token being locked
/// @param amount Amount of tokens being locked
/// @param permission Permission signature payload
function lock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(
getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce),
permission
)
{
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// add lock to storage
if (_lockSet.contains(lockID)) {
// if lock already exists, increase amount
_locks[lockID].balance = _locks[lockID].balance.add(amount);
} else {
// if does not exist, create new lock
// add lock to set
assert(_lockSet.add(lockID));
// add lock data to storage
_locks[lockID] = LockData(msg.sender, token, amount);
}
// validate sufficient balance
require(
IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance,
"UniversalVault: insufficient balance"
);
// increase nonce
_nonce += 1;
// emit event
emit Locked(msg.sender, token, amount);
}
/// @notice Unlock ERC20 tokens in the vault
/// access control: called by delegate with signed permission from owner
/// state machine: after valid lock from delegate
/// state scope:
/// - remove or update _locks
/// - increase _nonce
/// token transfer: none
/// @param token Address of token being unlocked
/// @param amount Amount of tokens being unlocked
/// @param permission Permission signature payload
function unlock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(
getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce),
permission
)
{
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVault: missing lock");
// update lock data
if (_locks[lockID].balance > amount) {
// substract amount from lock balance
_locks[lockID].balance = _locks[lockID].balance.sub(amount);
} else {
// delete lock data
delete _locks[lockID];
assert(_lockSet.remove(lockID));
}
// increase nonce
_nonce += 1;
// emit event
emit Unlocked(msg.sender, token, amount);
}
/// @notice Forcibly cancel delegate lock
/// @dev This function will attempt to notify the delegate of the rage quit using
/// a fixed amount of gas.
/// access control: only owner
/// state machine: after valid lock from delegate
/// state scope:
/// - remove item from _locks
/// token transfer: none
/// @param delegate Address of delegate
/// @param token Address of token being unlocked
function rageQuit(address delegate, address token)
external
override
onlyOwner
returns (bool notified, string memory error)
{
// get lock id
bytes32 lockID = calculateLockID(delegate, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVault: missing lock");
// attempt to notify delegate
if (delegate.isContract()) {
// check for sufficient gas
require(gasleft() >= RAGEQUIT_GAS, "UniversalVault: insufficient gas");
// attempt rageQuit notification
try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {
notified = true;
} catch Error(string memory res) {
notified = false;
error = res;
} catch (bytes memory) {
notified = false;
}
}
// update lock storage
assert(_lockSet.remove(lockID));
delete _locks[lockID];
// emit event
emit RageQuit(delegate, token, notified, error);
}
/// @notice Transfer ERC20 tokens out of vault
/// access control: only owner
/// state machine: when balance >= max(lock) + amount
/// state scope: none
/// token transfer: transfer any token
/// @param token Address of token being transferred
/// @param to Address of the recipient
/// @param amount Amount of tokens to transfer
function transferERC20(
address token,
address to,
uint256 amount
) external override onlyOwner {
// check for sufficient balance
require(
IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount),
"UniversalVault: insufficient balance"
);
// perform transfer
TransferHelper.safeTransfer(token, to, amount);
}
/// @notice Transfer ERC20 tokens out of vault
/// access control: only owner
/// state machine: when balance >= amount
/// state scope: none
/// token transfer: transfer any token
/// @param to Address of the recipient
/// @param amount Amount of ETH to transfer
function transferETH(address to, uint256 amount) external payable override onlyOwner {
// perform transfer
TransferHelper.safeTransferETH(to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev 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 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.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: MIT
pragma solidity ^0.7.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 () {
// 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.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev 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;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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.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.6.0 <0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/Address.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !Address.isContract(address(this));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/* solhint-disable max-line-length */
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private constant _TYPE_HASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal view virtual returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal view virtual returns (bytes32) {
return _HASHED_VERSION;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
interface IERC1271 {
function isValidSignature(bytes32 _messageHash, bytes memory _signature)
external
view
returns (bytes4 magicValue);
}
library SignatureChecker {
function isValidSignature(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
if (Address.isContract(signer)) {
bytes4 selector = IERC1271.isValidSignature.selector;
(bool success, bytes memory returndata) =
signer.staticcall(abi.encodeWithSelector(selector, hash, signature));
return success && abi.decode(returndata, (bytes4)) == selector;
} else {
return ECDSA.recover(hash, signature) == signer;
}
}
}
/// @title ERC1271
/// @notice Module for ERC1271 compatibility
abstract contract ERC1271 is IERC1271 {
// Valid magic value bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 internal constant VALID_SIG = IERC1271.isValidSignature.selector;
// Invalid magic value
bytes4 internal constant INVALID_SIG = bytes4(0);
modifier onlyValidSignature(bytes32 permissionHash, bytes memory signature) {
require(
isValidSignature(permissionHash, signature) == VALID_SIG,
"ERC1271: Invalid signature"
);
_;
}
function _getOwner() internal view virtual returns (address owner);
function isValidSignature(bytes32 permissionHash, bytes memory signature)
public
view
override
returns (bytes4)
{
return
SignatureChecker.isValidSignature(_getOwner(), permissionHash, signature)
? VALID_SIG
: INVALID_SIG;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/// @title OwnableERC721
/// @notice Use ERC721 ownership for access control
contract OwnableERC721 {
address private _nftAddress;
modifier onlyOwner() {
require(owner() == msg.sender, "OwnableERC721: caller is not the owner");
_;
}
function _setNFT(address nftAddress) internal {
_nftAddress = nftAddress;
}
function nft() public view virtual returns (address nftAddress) {
return _nftAddress;
}
function owner() public view virtual returns (address ownerAddress) {
return IERC721(_nftAddress).ownerOf(uint256(address(this)));
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {IFactory} from "../factory/IFactory.sol";
import {IInstanceRegistry} from "../factory/InstanceRegistry.sol";
import {IUniversalVault} from "../visor/Visor.sol";
import {IRewardPool} from "./RewardPool.sol";
import {Powered} from "./Powered.sol";
interface IRageQuit {
function rageQuit() external;
}
interface IHypervisor is IRageQuit {
/* admin events */
event HypervisorCreated(address rewardPool, address powerSwitch);
event HypervisorFunded(uint256 amount, uint256 duration);
event BonusTokenRegistered(address token);
event VaultFactoryRegistered(address factory);
event VaultFactoryRemoved(address factory);
/* user events */
event Staked(address vault, uint256 amount);
event Unstaked(address vault, uint256 amount);
event RewardClaimed(address vault, address recipient, address token, uint256 amount);
/* data types */
struct HypervisorData {
address stakingToken;
address rewardToken;
address rewardPool;
RewardScaling rewardScaling;
uint256 rewardSharesOutstanding;
uint256 totalStake;
uint256 totalStakeUnits;
uint256 lastUpdate;
RewardSchedule[] rewardSchedules;
}
struct RewardSchedule {
uint256 duration;
uint256 start;
uint256 shares;
}
struct VaultData {
uint256 totalStake;
StakeData[] stakes;
}
struct StakeData {
uint256 amount;
uint256 timestamp;
}
struct RewardScaling {
uint256 floor;
uint256 ceiling;
uint256 time;
}
struct RewardOutput {
uint256 lastStakeAmount;
uint256 newStakesCount;
uint256 reward;
uint256 newTotalStakeUnits;
}
/* user functions */
function stake(
address vault,
uint256 amount,
bytes calldata permission
) external;
function unstakeAndClaim(
address vault,
address recipient,
uint256 amount,
bytes calldata permission
) external;
/* getter functions */
function getHypervisorData() external view returns (HypervisorData memory hypervisor);
function getBonusTokenSetLength() external view returns (uint256 length);
function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);
function getVaultFactorySetLength() external view returns (uint256 length);
function getVaultFactoryAtIndex(uint256 index) external view returns (address factory);
function getVaultData(address vault) external view returns (VaultData memory vaultData);
function isValidAddress(address target) external view returns (bool validity);
function isValidVault(address target) external view returns (bool validity);
function getCurrentUnlockedRewards() external view returns (uint256 unlockedRewards);
function getFutureUnlockedRewards(uint256 timestamp)
external
view
returns (uint256 unlockedRewards);
function getCurrentVaultReward(address vault) external view returns (uint256 reward);
function getCurrentStakeReward(address vault, uint256 stakeAmount)
external
view
returns (uint256 reward);
function getFutureVaultReward(address vault, uint256 timestamp)
external
view
returns (uint256 reward);
function getFutureStakeReward(
address vault,
uint256 stakeAmount,
uint256 timestamp
) external view returns (uint256 reward);
function getCurrentVaultStakeUnits(address vault) external view returns (uint256 stakeUnits);
function getFutureVaultStakeUnits(address vault, uint256 timestamp)
external
view
returns (uint256 stakeUnits);
function getCurrentTotalStakeUnits() external view returns (uint256 totalStakeUnits);
function getFutureTotalStakeUnits(uint256 timestamp)
external
view
returns (uint256 totalStakeUnits);
/* pure functions */
function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)
external
pure
returns (uint256 totalStakeUnits);
function calculateStakeUnits(
uint256 amount,
uint256 start,
uint256 end
) external pure returns (uint256 stakeUnits);
function calculateUnlockedRewards(
RewardSchedule[] memory rewardSchedules,
uint256 rewardBalance,
uint256 sharesOutstanding,
uint256 timestamp
) external pure returns (uint256 unlockedRewards);
function calculateRewardFromStakes(
StakeData[] memory stakes,
uint256 unstakeAmount,
uint256 unlockedRewards,
uint256 totalStakeUnits,
uint256 timestamp,
RewardScaling memory rewardScaling
) external pure returns (RewardOutput memory out);
function calculateReward(
uint256 unlockedRewards,
uint256 stakeAmount,
uint256 stakeDuration,
uint256 totalStakeUnits,
RewardScaling memory rewardScaling
) external pure returns (uint256 reward);
}
/// @title Hypervisor
/// @notice Reward distribution contract with time multiplier
/// Access Control
/// - Power controller:
/// Can power off / shutdown the Hypervisor
/// Can withdraw rewards from reward pool once shutdown
/// - Proxy owner:
/// Can change arbitrary logic / state by upgrading the Hypervisor
/// Is unable to operate on user funds due to UniversalVault
/// Is unable to operate on reward pool funds when reward pool is offline / shutdown
/// - Hypervisor admin:
/// Can add funds to the Hypervisor, register bonus tokens, and whitelist new vault factories
/// Is a subset of proxy owner permissions
/// - User:
/// Can deposit / withdraw / ragequit
/// Hypervisor State Machine
/// - Online:
/// Hypervisor is operating normally, all functions are enabled
/// - Offline:
/// Hypervisor is temporarely disabled for maintenance
/// User deposits and withdrawls are disabled, ragequit remains enabled
/// Users can withdraw their stake through rageQuit() but forego their pending reward
/// Should only be used when downtime required for an upgrade
/// - Shutdown:
/// Hypervisor is permanently disabled
/// All functions are disabled with the exception of ragequit
/// Users can withdraw their stake through rageQuit()
/// Power controller can withdraw from the reward pool
/// Should only be used if Proxy Owner role is compromized
contract Hypervisor is IHypervisor, Powered, Ownable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/* constants */
// An upper bound on the number of active stakes per vault is required to prevent
// calls to rageQuit() from reverting.
// With 30 stakes in a vault, ragequit costs 432811 gas which is conservatively lower
// than the hardcoded limit of 500k gas on the vault.
// This limit is configurable and could be increased in a future deployment.
// Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public constant MAX_STAKES_PER_VAULT = 30;
uint256 public constant MAX_REWARD_TOKENS = 50;
uint256 public constant BASE_SHARES_PER_WEI = 1000000;
/* storage */
HypervisorData private _hypervisor;
mapping(address => VaultData) private _vaults;
EnumerableSet.AddressSet private _bonusTokenSet;
EnumerableSet.AddressSet private _vaultFactorySet;
/* initializer */
/// @notice Initizalize Hypervisor
/// access control: only proxy constructor
/// state machine: can only be called once
/// state scope: set initialization variables
/// token transfer: none
/// @param ownerAddress address The admin address
/// @param rewardPoolFactory address The factory to use for deploying the RewardPool
/// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch
/// @param stakingToken address The address of the staking token for this Hypervisor
/// @param rewardToken address The address of the reward token for this Hypervisor
/// @param rewardScaling RewardScaling The config for reward scaling floor, ceiling, and time
constructor(
address ownerAddress,
address rewardPoolFactory,
address powerSwitchFactory,
address stakingToken,
address rewardToken,
RewardScaling memory rewardScaling
) {
// the scaling floor must be smaller than ceiling
require(rewardScaling.floor <= rewardScaling.ceiling, "Hypervisor: floor above ceiling");
// setting rewardScalingTime to 0 would cause divide by zero error
// to disable reward scaling, use rewardScalingFloor == rewardScalingCeiling
require(rewardScaling.time != 0, "Hypervisor: scaling time cannot be zero");
// deploy power switch
address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(ownerAddress));
// deploy reward pool
address rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));
// set internal configs
Ownable.transferOwnership(ownerAddress);
Powered._setPowerSwitch(powerSwitch);
// commit to storage
_hypervisor.stakingToken = stakingToken;
_hypervisor.rewardToken = rewardToken;
_hypervisor.rewardPool = rewardPool;
_hypervisor.rewardScaling = rewardScaling;
// emit event
emit HypervisorCreated(rewardPool, powerSwitch);
}
/* getter functions */
function getBonusTokenSetLength() external view override returns (uint256 length) {
return _bonusTokenSet.length();
}
function getBonusTokenAtIndex(uint256 index)
external
view
override
returns (address bonusToken)
{
return _bonusTokenSet.at(index);
}
function getVaultFactorySetLength() external view override returns (uint256 length) {
return _vaultFactorySet.length();
}
function getVaultFactoryAtIndex(uint256 index)
external
view
override
returns (address factory)
{
return _vaultFactorySet.at(index);
}
function isValidVault(address target) public view override returns (bool validity) {
// validate target is created from whitelisted vault factory
for (uint256 index = 0; index < _vaultFactorySet.length(); index++) {
if (IInstanceRegistry(_vaultFactorySet.at(index)).isInstance(target)) {
return true;
}
}
// explicit return
return false;
}
function isValidAddress(address target) public view override returns (bool validity) {
// sanity check target for potential input errors
return
target != address(this) &&
target != address(0) &&
target != _hypervisor.stakingToken &&
target != _hypervisor.rewardToken &&
target != _hypervisor.rewardPool &&
!_bonusTokenSet.contains(target);
}
/* Hypervisor getters */
function getHypervisorData() external view override returns (HypervisorData memory hypervisor) {
return _hypervisor;
}
function getCurrentUnlockedRewards() public view override returns (uint256 unlockedRewards) {
// calculate reward available based on state
return getFutureUnlockedRewards(block.timestamp);
}
function getFutureUnlockedRewards(uint256 timestamp)
public
view
override
returns (uint256 unlockedRewards)
{
// get reward amount remaining
uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);
// calculate reward available based on state
unlockedRewards = calculateUnlockedRewards(
_hypervisor.rewardSchedules,
remainingRewards,
_hypervisor.rewardSharesOutstanding,
timestamp
);
// explicit return
return unlockedRewards;
}
function getCurrentTotalStakeUnits() public view override returns (uint256 totalStakeUnits) {
// calculate new stake units
return getFutureTotalStakeUnits(block.timestamp);
}
function getFutureTotalStakeUnits(uint256 timestamp)
public
view
override
returns (uint256 totalStakeUnits)
{
// return early if no change
if (timestamp == _hypervisor.lastUpdate) return _hypervisor.totalStakeUnits;
// calculate new stake units
uint256 newStakeUnits =
calculateStakeUnits(_hypervisor.totalStake, _hypervisor.lastUpdate, timestamp);
// add to cached total
totalStakeUnits = _hypervisor.totalStakeUnits.add(newStakeUnits);
// explicit return
return totalStakeUnits;
}
/* vault getters */
function getVaultData(address vault)
external
view
override
returns (VaultData memory vaultData)
{
return _vaults[vault];
}
function getCurrentVaultReward(address vault) external view override returns (uint256 reward) {
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
_vaults[vault]
.totalStake,
getCurrentUnlockedRewards(),
getCurrentTotalStakeUnits(),
block
.timestamp,
_hypervisor
.rewardScaling
)
.reward;
}
function getFutureVaultReward(address vault, uint256 timestamp)
external
view
override
returns (uint256 reward)
{
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
_vaults[vault]
.totalStake,
getFutureUnlockedRewards(timestamp),
getFutureTotalStakeUnits(timestamp),
timestamp,
_hypervisor
.rewardScaling
)
.reward;
}
function getCurrentStakeReward(address vault, uint256 stakeAmount)
external
view
override
returns (uint256 reward)
{
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
stakeAmount,
getCurrentUnlockedRewards(),
getCurrentTotalStakeUnits(),
block
.timestamp,
_hypervisor
.rewardScaling
)
.reward;
}
function getFutureStakeReward(
address vault,
uint256 stakeAmount,
uint256 timestamp
) external view override returns (uint256 reward) {
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
stakeAmount,
getFutureUnlockedRewards(timestamp),
getFutureTotalStakeUnits(timestamp),
timestamp,
_hypervisor
.rewardScaling
)
.reward;
}
function getCurrentVaultStakeUnits(address vault)
public
view
override
returns (uint256 stakeUnits)
{
// calculate stake units
return getFutureVaultStakeUnits(vault, block.timestamp);
}
function getFutureVaultStakeUnits(address vault, uint256 timestamp)
public
view
override
returns (uint256 stakeUnits)
{
// calculate stake units
return calculateTotalStakeUnits(_vaults[vault].stakes, timestamp);
}
/* pure functions */
function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)
public
pure
override
returns (uint256 totalStakeUnits)
{
for (uint256 index; index < stakes.length; index++) {
// reference stake
StakeData memory stakeData = stakes[index];
// calculate stake units
uint256 stakeUnits =
calculateStakeUnits(stakeData.amount, stakeData.timestamp, timestamp);
// add to running total
totalStakeUnits = totalStakeUnits.add(stakeUnits);
}
}
function calculateStakeUnits(
uint256 amount,
uint256 start,
uint256 end
) public pure override returns (uint256 stakeUnits) {
// calculate duration
uint256 duration = end.sub(start);
// calculate stake units
stakeUnits = duration.mul(amount);
// explicit return
return stakeUnits;
}
function calculateUnlockedRewards(
RewardSchedule[] memory rewardSchedules,
uint256 rewardBalance,
uint256 sharesOutstanding,
uint256 timestamp
) public pure override returns (uint256 unlockedRewards) {
// return 0 if no registered schedules
if (rewardSchedules.length == 0) {
return 0;
}
// calculate reward shares locked across all reward schedules
uint256 sharesLocked;
for (uint256 index = 0; index < rewardSchedules.length; index++) {
// fetch reward schedule storage reference
RewardSchedule memory schedule = rewardSchedules[index];
// caculate amount of shares available on this schedule
// if (now - start) < duration
// sharesLocked = shares - (shares * (now - start) / duration)
// else
// sharesLocked = 0
uint256 currentSharesLocked = 0;
if (timestamp.sub(schedule.start) < schedule.duration) {
currentSharesLocked = schedule.shares.sub(
schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration)
);
}
// add to running total
sharesLocked = sharesLocked.add(currentSharesLocked);
}
// convert shares to reward
// rewardLocked = sharesLocked * rewardBalance / sharesOutstanding
uint256 rewardLocked = sharesLocked.mul(rewardBalance).div(sharesOutstanding);
// calculate amount available
// unlockedRewards = rewardBalance - rewardLocked
unlockedRewards = rewardBalance.sub(rewardLocked);
// explicit return
return unlockedRewards;
}
function calculateRewardFromStakes(
StakeData[] memory stakes,
uint256 unstakeAmount,
uint256 unlockedRewards,
uint256 totalStakeUnits,
uint256 timestamp,
RewardScaling memory rewardScaling
) public pure override returns (RewardOutput memory out) {
uint256 stakesToDrop = 0;
while (unstakeAmount > 0) {
// fetch vault stake storage reference
StakeData memory lastStake = stakes[stakes.length.sub(stakesToDrop).sub(1)];
// calculate stake duration
uint256 stakeDuration = timestamp.sub(lastStake.timestamp);
uint256 currentAmount;
if (lastStake.amount > unstakeAmount) {
// set current amount to remaining unstake amount
currentAmount = unstakeAmount;
// amount of last stake is reduced
out.lastStakeAmount = lastStake.amount.sub(unstakeAmount);
} else {
// set current amount to amount of last stake
currentAmount = lastStake.amount;
// add to stakes to drop
stakesToDrop += 1;
}
// update remaining unstakeAmount
unstakeAmount = unstakeAmount.sub(currentAmount);
// calculate reward amount
uint256 currentReward =
calculateReward(
unlockedRewards,
currentAmount,
stakeDuration,
totalStakeUnits,
rewardScaling
);
// update cumulative reward
out.reward = out.reward.add(currentReward);
// update cached unlockedRewards
unlockedRewards = unlockedRewards.sub(currentReward);
// calculate time weighted stake
uint256 stakeUnits = currentAmount.mul(stakeDuration);
// update cached totalStakeUnits
totalStakeUnits = totalStakeUnits.sub(stakeUnits);
}
// explicit return
return
RewardOutput(
out.lastStakeAmount,
stakes.length.sub(stakesToDrop),
out.reward,
totalStakeUnits
);
}
function calculateReward(
uint256 unlockedRewards,
uint256 stakeAmount,
uint256 stakeDuration,
uint256 totalStakeUnits,
RewardScaling memory rewardScaling
) public pure override returns (uint256 reward) {
// calculate time weighted stake
uint256 stakeUnits = stakeAmount.mul(stakeDuration);
// calculate base reward
// baseReward = unlockedRewards * stakeUnits / totalStakeUnits
uint256 baseReward = 0;
if (totalStakeUnits != 0) {
// scale reward according to proportional weight
baseReward = unlockedRewards.mul(stakeUnits).div(totalStakeUnits);
}
// calculate scaled reward
// if no scaling or scaling period completed
// reward = baseReward
// else
// minReward = baseReward * scalingFloor / scalingCeiling
// bonusReward = baseReward
// * (scalingCeiling - scalingFloor) / scalingCeiling
// * duration / scalingTime
// reward = minReward + bonusReward
if (stakeDuration >= rewardScaling.time || rewardScaling.floor == rewardScaling.ceiling) {
// no reward scaling applied
reward = baseReward;
} else {
// calculate minimum reward using scaling floor
uint256 minReward = baseReward.mul(rewardScaling.floor).div(rewardScaling.ceiling);
// calculate bonus reward with vested portion of scaling factor
uint256 bonusReward =
baseReward
.mul(stakeDuration)
.mul(rewardScaling.ceiling.sub(rewardScaling.floor))
.div(rewardScaling.ceiling)
.div(rewardScaling.time);
// add minimum reward and bonus reward
reward = minReward.add(bonusReward);
}
// explicit return
return reward;
}
/* admin functions */
/// @notice Add funds to the Hypervisor
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - increase _hypervisor.rewardSharesOutstanding
/// - append to _hypervisor.rewardSchedules
/// token transfer: transfer staking tokens from msg.sender to reward pool
/// @param amount uint256 Amount of reward tokens to deposit
/// @param duration uint256 Duration over which to linearly unlock rewards
function fund(uint256 amount, uint256 duration) external onlyOwner onlyOnline {
// validate duration
require(duration != 0, "Hypervisor: invalid duration");
// create new reward shares
// if existing rewards on this Hypervisor
// mint new shares proportional to % change in rewards remaining
// newShares = remainingShares * newReward / remainingRewards
// else
// mint new shares with BASE_SHARES_PER_WEI initial conversion rate
// store as fixed point number with same of decimals as reward token
uint256 newRewardShares;
if (_hypervisor.rewardSharesOutstanding > 0) {
uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);
newRewardShares = _hypervisor.rewardSharesOutstanding.mul(amount).div(remainingRewards);
} else {
newRewardShares = amount.mul(BASE_SHARES_PER_WEI);
}
// add reward shares to total
_hypervisor.rewardSharesOutstanding = _hypervisor.rewardSharesOutstanding.add(newRewardShares);
// store new reward schedule
_hypervisor.rewardSchedules.push(RewardSchedule(duration, block.timestamp, newRewardShares));
// transfer reward tokens to reward pool
TransferHelper.safeTransferFrom(
_hypervisor.rewardToken,
msg.sender,
_hypervisor.rewardPool,
amount
);
// emit event
emit HypervisorFunded(amount, duration);
}
/// @notice Add vault factory to whitelist
/// @dev use this function to enable stakes to vaults coming from the specified
/// factory contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - append to _vaultFactorySet
/// token transfer: none
/// @param factory address The address of the vault factory
function registerVaultFactory(address factory) external onlyOwner notShutdown {
// add factory to set
require(_vaultFactorySet.add(factory), "Hypervisor: vault factory already registered");
// emit event
emit VaultFactoryRegistered(factory);
}
/// @notice Remove vault factory from whitelist
/// @dev use this function to disable new stakes to vaults coming from the specified
/// factory contract.
/// note: vaults with existing stakes from this factory are sill able to unstake
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - remove from _vaultFactorySet
/// token transfer: none
/// @param factory address The address of the vault factory
function removeVaultFactory(address factory) external onlyOwner notShutdown {
// remove factory from set
require(_vaultFactorySet.remove(factory), "Hypervisor: vault factory not registered");
// emit event
emit VaultFactoryRemoved(factory);
}
/// @notice Register bonus token for distribution
/// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - append to _bonusTokenSet
/// token transfer: none
/// @param bonusToken address The address of the bonus token
function registerBonusToken(address bonusToken) external onlyOwner onlyOnline {
// verify valid bonus token
_validateAddress(bonusToken);
// verify bonus token count
require(_bonusTokenSet.length() < MAX_REWARD_TOKENS, "Hypervisor: max bonus tokens reached ");
// add token to set
assert(_bonusTokenSet.add(bonusToken));
// emit event
emit BonusTokenRegistered(bonusToken);
}
/// @notice Rescue tokens from RewardPool
/// @dev use this function to rescue tokens from RewardPool contract
/// without distributing to stakers or triggering emergency shutdown
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope: none
/// token transfer: transfer requested token from RewardPool to recipient
/// @param token address The address of the token to rescue
/// @param recipient address The address of the recipient
/// @param amount uint256 The amount of tokens to rescue
function rescueTokensFromRewardPool(
address token,
address recipient,
uint256 amount
) external onlyOwner onlyOnline {
// verify recipient
_validateAddress(recipient);
// check not attempting to unstake reward token
require(token != _hypervisor.rewardToken, "Hypervisor: invalid address");
// check not attempting to wthdraw bonus token
require(!_bonusTokenSet.contains(token), "Hypervisor: invalid address");
// transfer tokens to recipient
IRewardPool(_hypervisor.rewardPool).sendERC20(token, recipient, amount);
}
/* user functions */
/// @notice Stake tokens
/// @dev anyone can stake to any vault if they have valid permission
/// access control: anyone
/// state machine:
/// - can be called multiple times
/// - only online
/// - when vault exists on this Hypervisor
/// state scope:
/// - append to _vaults[vault].stakes
/// - increase _vaults[vault].totalStake
/// - increase _hypervisor.totalStake
/// - increase _hypervisor.totalStakeUnits
/// - increase _hypervisor.lastUpdate
/// token transfer: transfer staking tokens from msg.sender to vault
/// @param vault address The address of the vault to stake from
/// @param amount uint256 The amount of staking tokens to stake
function stake(
address vault,
uint256 amount,
bytes calldata permission
) external override onlyOnline {
// verify vault is valid
require(isValidVault(vault), "Hypervisor: vault is not registered");
// verify non-zero amount
require(amount != 0, "Hypervisor: no amount staked");
// fetch vault storage reference
VaultData storage vaultData = _vaults[vault];
// verify stakes boundary not reached
require(
vaultData.stakes.length < MAX_STAKES_PER_VAULT,
"Hypervisor: MAX_STAKES_PER_VAULT reached"
);
// update cached sum of stake units across all vaults
_updateTotalStakeUnits();
// store amount and timestamp
vaultData.stakes.push(StakeData(amount, block.timestamp));
// update cached total vault and Hypervisor amounts
vaultData.totalStake = vaultData.totalStake.add(amount);
_hypervisor.totalStake = _hypervisor.totalStake.add(amount);
// call lock on vault
IUniversalVault(vault).lock(_hypervisor.stakingToken, amount, permission);
// emit event
emit Staked(vault, amount);
}
/// @notice Unstake staking tokens and claim reward
/// @dev rewards can only be claimed when unstaking
/// access control: only owner of vault
/// state machine:
/// - when vault exists on this Hypervisor
/// - after stake from vault
/// - can be called multiple times while sufficient stake remains
/// - only online
/// state scope:
/// - decrease _hypervisor.rewardSharesOutstanding
/// - decrease _hypervisor.totalStake
/// - increase _hypervisor.lastUpdate
/// - modify _hypervisor.totalStakeUnits
/// - modify _vaults[vault].stakes
/// - decrease _vaults[vault].totalStake
/// token transfer:
/// - transfer reward tokens from reward pool to recipient
/// - transfer bonus tokens from reward pool to recipient
/// @param vault address The vault to unstake from
/// @param recipient address The recipient to send reward to
/// @param amount uint256 The amount of staking tokens to unstake
function unstakeAndClaim(
address vault,
address recipient,
uint256 amount,
bytes calldata permission
) external override onlyOnline {
// fetch vault storage reference
VaultData storage vaultData = _vaults[vault];
// verify non-zero amount
require(amount != 0, "Hypervisor: no amount unstaked");
// validate recipient
_validateAddress(recipient);
// check for sufficient vault stake amount
require(vaultData.totalStake >= amount, "Hypervisor: insufficient vault stake");
// check for sufficient Hypervisor stake amount
// if this check fails, there is a bug in stake accounting
assert(_hypervisor.totalStake >= amount);
// update cached sum of stake units across all vaults
_updateTotalStakeUnits();
// get reward amount remaining
uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);
// calculate vested portion of reward pool
uint256 unlockedRewards =
calculateUnlockedRewards(
_hypervisor.rewardSchedules,
remainingRewards,
_hypervisor.rewardSharesOutstanding,
block.timestamp
);
// calculate vault time weighted reward with scaling
RewardOutput memory out =
calculateRewardFromStakes(
vaultData.stakes,
amount,
unlockedRewards,
_hypervisor.totalStakeUnits,
block.timestamp,
_hypervisor.rewardScaling
);
// update stake data in storage
if (out.newStakesCount == 0) {
// all stakes have been unstaked
delete vaultData.stakes;
} else {
// some stakes have been completely or partially unstaked
// delete fully unstaked stakes
while (vaultData.stakes.length > out.newStakesCount) vaultData.stakes.pop();
// update partially unstaked stake
vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount;
}
// update cached stake totals
vaultData.totalStake = vaultData.totalStake.sub(amount);
_hypervisor.totalStake = _hypervisor.totalStake.sub(amount);
_hypervisor.totalStakeUnits = out.newTotalStakeUnits;
// unlock staking tokens from vault
IUniversalVault(vault).unlock(_hypervisor.stakingToken, amount, permission);
// emit event
emit Unstaked(vault, amount);
// only perform on non-zero reward
if (out.reward > 0) {
// calculate shares to burn
// sharesToBurn = sharesOutstanding * reward / remainingRewards
uint256 sharesToBurn =
_hypervisor.rewardSharesOutstanding.mul(out.reward).div(remainingRewards);
// burn claimed shares
_hypervisor.rewardSharesOutstanding = _hypervisor.rewardSharesOutstanding.sub(sharesToBurn);
// transfer bonus tokens from reward pool to recipient
if (_bonusTokenSet.length() > 0) {
for (uint256 index = 0; index < _bonusTokenSet.length(); index++) {
// fetch bonus token address reference
address bonusToken = _bonusTokenSet.at(index);
// calculate bonus token amount
// bonusAmount = bonusRemaining * reward / remainingRewards
uint256 bonusAmount =
IERC20(bonusToken).balanceOf(_hypervisor.rewardPool).mul(out.reward).div(
remainingRewards
);
// transfer bonus token
IRewardPool(_hypervisor.rewardPool).sendERC20(bonusToken, recipient, bonusAmount);
// emit event
emit RewardClaimed(vault, recipient, bonusToken, bonusAmount);
}
}
// transfer reward tokens from reward pool to recipient
IRewardPool(_hypervisor.rewardPool).sendERC20(_hypervisor.rewardToken, recipient, out.reward);
// emit event
emit RewardClaimed(vault, recipient, _hypervisor.rewardToken, out.reward);
}
}
/// @notice Exit Hypervisor without claiming reward
/// @dev This function should never revert when correctly called by the vault.
/// A max number of stakes per vault is set with MAX_STAKES_PER_VAULT to
/// place an upper bound on the for loop in calculateTotalStakeUnits().
/// access control: only callable by the vault directly
/// state machine:
/// - when vault exists on this Hypervisor
/// - when active stake from this vault
/// - any power state
/// state scope:
/// - decrease _hypervisor.totalStake
/// - increase _hypervisor.lastUpdate
/// - modify _hypervisor.totalStakeUnits
/// - delete _vaults[vault]
/// token transfer: none
function rageQuit() external override {
// fetch vault storage reference
VaultData storage _vaultData = _vaults[msg.sender];
// revert if no active stakes
require(_vaultData.stakes.length != 0, "Hypervisor: no stake");
// update cached sum of stake units across all vaults
_updateTotalStakeUnits();
// emit event
emit Unstaked(msg.sender, _vaultData.totalStake);
// update cached totals
_hypervisor.totalStake = _hypervisor.totalStake.sub(_vaultData.totalStake);
_hypervisor.totalStakeUnits = _hypervisor.totalStakeUnits.sub(
calculateTotalStakeUnits(_vaultData.stakes, block.timestamp)
);
// delete stake data
delete _vaults[msg.sender];
}
/* convenience functions */
function _updateTotalStakeUnits() private {
// update cached totalStakeUnits
_hypervisor.totalStakeUnits = getCurrentTotalStakeUnits();
// update cached lastUpdate
_hypervisor.lastUpdate = block.timestamp;
}
function _validateAddress(address target) private view {
// sanity check target for potential input errors
require(isValidAddress(target), "Hypervisor: invalid address");
}
function _truncateStakesArray(StakeData[] memory array, uint256 newLength)
private
pure
returns (StakeData[] memory newArray)
{
newArray = new StakeData[](newLength);
for (uint256 index = 0; index < newLength; index++) {
newArray[index] = array[index];
}
return newArray;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n รท 2 + 1, and for v in (282): v โ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {Powered} from "./Powered.sol";
interface IRewardPool {
function sendERC20(
address token,
address to,
uint256 value
) external;
function rescueERC20(address[] calldata tokens, address recipient) external;
}
/// @title Reward Pool
/// @notice Vault for isolated storage of reward tokens
contract RewardPool is IRewardPool, Powered, Ownable {
/* initializer */
constructor(address powerSwitch) {
Powered._setPowerSwitch(powerSwitch);
}
/* user functions */
/// @notice Send an ERC20 token
/// access control: only owner
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope: none
/// token transfer: transfer tokens from self to recipient
/// @param token address The token to send
/// @param to address The recipient to send to
/// @param value uint256 Amount of tokens to send
function sendERC20(
address token,
address to,
uint256 value
) external override onlyOwner onlyOnline {
TransferHelper.safeTransfer(token, to, value);
}
/* emergency functions */
/// @notice Rescue multiple ERC20 tokens
/// access control: only power controller
/// state machine:
/// - can be called multiple times
/// - only shutdown
/// state scope: none
/// token transfer: transfer tokens from self to recipient
/// @param tokens address[] The tokens to rescue
/// @param recipient address The recipient to rescue to
function rescueERC20(address[] calldata tokens, address recipient)
external
override
onlyShutdown
{
// only callable by controller
require(
msg.sender == Powered.getPowerController(),
"RewardPool: only controller can withdraw after shutdown"
);
// assert recipient is defined
require(recipient != address(0), "RewardPool: recipient not defined");
// transfer tokens
for (uint256 index = 0; index < tokens.length; index++) {
// get token
address token = tokens[index];
// get balance
uint256 balance = IERC20(token).balanceOf(address(this));
// transfer token
TransferHelper.safeTransfer(token, recipient, balance);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IPowerSwitch} from "./PowerSwitch.sol";
interface IPowered {
function isOnline() external view returns (bool status);
function isOffline() external view returns (bool status);
function isShutdown() external view returns (bool status);
function getPowerSwitch() external view returns (address powerSwitch);
function getPowerController() external view returns (address controller);
}
/// @title Powered
/// @notice Helper for calling external PowerSwitch
contract Powered is IPowered {
/* storage */
address private _powerSwitch;
/* modifiers */
modifier onlyOnline() {
_onlyOnline();
_;
}
modifier onlyOffline() {
_onlyOffline();
_;
}
modifier notShutdown() {
_notShutdown();
_;
}
modifier onlyShutdown() {
_onlyShutdown();
_;
}
/* initializer */
function _setPowerSwitch(address powerSwitch) internal {
_powerSwitch = powerSwitch;
}
/* getter functions */
function isOnline() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isOnline();
}
function isOffline() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isOffline();
}
function isShutdown() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isShutdown();
}
function getPowerSwitch() public view override returns (address powerSwitch) {
return _powerSwitch;
}
function getPowerController() public view override returns (address controller) {
return IPowerSwitch(_powerSwitch).getPowerController();
}
/* convenience functions */
function _onlyOnline() private view {
require(isOnline(), "Powered: is not online");
}
function _onlyOffline() private view {
require(isOffline(), "Powered: is not offline");
}
function _notShutdown() private view {
require(!isShutdown(), "Powered: is shutdown");
}
function _onlyShutdown() private view {
require(isShutdown(), "Powered: is not shutdown");
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
interface IPowerSwitch {
/* admin events */
event PowerOn();
event PowerOff();
event EmergencyShutdown();
/* data types */
enum State {Online, Offline, Shutdown}
/* admin functions */
function powerOn() external;
function powerOff() external;
function emergencyShutdown() external;
/* view functions */
function isOnline() external view returns (bool status);
function isOffline() external view returns (bool status);
function isShutdown() external view returns (bool status);
function getStatus() external view returns (State status);
function getPowerController() external view returns (address controller);
}
/// @title PowerSwitch
/// @notice Standalone pausing and emergency stop functionality
contract PowerSwitch is IPowerSwitch, Ownable {
/* storage */
IPowerSwitch.State private _status;
/* initializer */
constructor(address owner) {
// sanity check owner
require(owner != address(0), "PowerSwitch: invalid owner");
// transfer ownership
Ownable.transferOwnership(owner);
}
/* admin functions */
/// @notice Turn Power On
/// access control: only admin
/// state machine: only when offline
/// state scope: only modify _status
/// token transfer: none
function powerOn() external override onlyOwner {
require(_status == IPowerSwitch.State.Offline, "PowerSwitch: cannot power on");
_status = IPowerSwitch.State.Online;
emit PowerOn();
}
/// @notice Turn Power Off
/// access control: only admin
/// state machine: only when online
/// state scope: only modify _status
/// token transfer: none
function powerOff() external override onlyOwner {
require(_status == IPowerSwitch.State.Online, "PowerSwitch: cannot power off");
_status = IPowerSwitch.State.Offline;
emit PowerOff();
}
/// @notice Shutdown Permanently
/// access control: only admin
/// state machine:
/// - when online or offline
/// - can only be called once
/// state scope: only modify _status
/// token transfer: none
function emergencyShutdown() external override onlyOwner {
require(_status != IPowerSwitch.State.Shutdown, "PowerSwitch: cannot shutdown");
_status = IPowerSwitch.State.Shutdown;
emit EmergencyShutdown();
}
/* getter functions */
function isOnline() external view override returns (bool status) {
return _status == State.Online;
}
function isOffline() external view override returns (bool status) {
return _status == State.Offline;
}
function isShutdown() external view override returns (bool status) {
return _status == State.Shutdown;
}
function getStatus() external view override returns (IPowerSwitch.State status) {
return _status;
}
function getPowerController() external view override returns (address controller) {
return Ownable.owner();
}
}
|
Add funds to the Hypervisor access control: only admin state machine: - can be called multiple times - only online state scope: - increase _hypervisor.rewardSharesOutstanding - append to _hypervisor.rewardSchedules token transfer: transfer staking tokens from msg.sender to reward pool amount uint256 Amount of reward tokens to deposit duration uint256 Duration over which to linearly unlock rewards validate duration create new reward shares if existing rewards on this Hypervisor mint new shares proportional to % change in rewards remaining newShares = remainingShares newReward / remainingRewards else mint new shares with BASE_SHARES_PER_WEI initial conversion rate store as fixed point number with same of decimals as reward token
|
function fund(uint256 amount, uint256 duration) external onlyOwner onlyOnline {
require(duration != 0, "Hypervisor: invalid duration");
uint256 newRewardShares;
if (_hypervisor.rewardSharesOutstanding > 0) {
uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);
newRewardShares = _hypervisor.rewardSharesOutstanding.mul(amount).div(remainingRewards);
newRewardShares = amount.mul(BASE_SHARES_PER_WEI);
}
_hypervisor.rewardToken,
msg.sender,
_hypervisor.rewardPool,
amount
);
}
| 184,081
|
./full_match/80001/0xe7Ebc638409b8f4f0DAde04c16e843a94bBc667e/sources/src/Access.sol
|
Revokes role from an account. Caller must have admin role for the `role`. Emits {RoleRevoked Event}. role keccak256 hash of the role. e.g. keccak256("TRANSFER_ROLE") account Address of the account from which the role is being revoked./
|
function revokeRole(bytes32 role, address account)
public
virtual
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
if (role == ADMIN_ROLE()) {
removeAddr(admins, account);
}
_revokeRole(role, account);
}
| 5,606,042
|
./full_match/1/0xAAf570aAB5B578D84441E9269d2953B5b2759b4a/sources/contracts/VitalFusion.sol
|
Airdrop functionality for the contract owner. Owner airdrop with no checks other than those included in _internalMint()
|
function ownerAirdrop(address[] memory wallets, uint[] calldata tokens) external onlyOwner nonReentrant {
require(wallets.length == tokens.length, "Airdrop wallets must have assocaited token assignment.");
uint256 w;
for (w = 0; w < wallets.length; w++) {
_internalMint(wallets[w], tokens[w]);
}
}
| 4,977,792
|
./full_match/137/0x74E7ACAfC758caC65910e5C38E6Ef9ade5fA87A8/sources/contracts/SpotTradingRewardDistributor/SpotTradingRewardDistributor.sol
|
@inheritdoc ISpotTradingRewardDistributor/
|
function setRewardPerPeriod(uint256 _rewardPerPeriod) external override onlyRole(MEDIUM_TIMELOCK_ADMIN) {
rewardPerPeriod = _rewardPerPeriod;
emit RewardPerPeriodChanged(_rewardPerPeriod);
}
| 4,721,650
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./ERC721A.sol";
import "./StakeApe.sol";
import "./IAgency.sol";
import "hardhat/console.sol";
interface ITokenBall {
function mintReward(address recipient, uint amount) external;
function burnMoney(address recipient, uint amount) external;
}
/**
* Headquarter of the New Basketball Ape Young Crew Agency
* Organize matches, stakes the Apes for available for rent, sends rewards, etc
*/
contract NbaycAgency is IAgency, Ownable, ERC721A, ReentrancyGuard {
address apeAddress;
address ballAddress;
bool closed = false;
mapping(address => bool) admins;
uint private maxSupply = 5000;
mapping(uint => StakeApe) idToStakeApe;
mapping(address => uint[]) ownerToArrTokenIds;
constructor(address adminAddr, address _ape, address _ball) ERC721A("NBAYCAgency", "NBAYCA", 10, 50000) ReentrancyGuard() {
admins[adminAddr] = true;
apeAddress = _ape;
ballAddress = _ball;
}
//
//// Utility functions
//
/** Put Apes into agency. Will transfer 721 tokens to the agency in order to play.
*/
function putApesToAgency(uint[] memory ids, address owner) override external onlyAdmin {
require(!closed, "The agency is closed. No more Apes can come in for now ;)");
for (uint i = 0; i < ids.length; i++) {
require(IERC721(apeAddress).ownerOf(ids[i]) == owner, "You cannot add an Ape that is not yours ...");
idToStakeApe[ids[i]] = StakeApe(ids[i], owner, 'N', 0);
ownerToArrTokenIds[owner].push(ids[i]);
IERC721(apeAddress).transferFrom(
owner,
address(this),
ids[i]
);
}
}
/** Transfer back the Apes from the Agency to original owner's wallet.
*/
function getApesFromAgency(uint[] memory ids, address owner) override external onlyAdmin {
for (uint i = 0; i < ids.length; i++) {
// require(idToStakeApe[ids[i]].owner == owner, "You cannot return an Ape that is not his ...");
require(idToStakeApe[ids[i]].state == 'N', "This Ape is not on bench ... Stop his activity before.");
delete idToStakeApe[ids[i]];
removeTokenToOwner(owner, ids[i]);
IERC721(apeAddress).transferFrom(
address(this),
owner,
ids[i]
);
}
}
//
// Get/Set functions :
//
function removeTokenToOwner(address owner, uint element) private {
bool r = false;
for (uint256 i = 0; i < ownerToArrTokenIds[owner].length - 1; i++) {
if (ownerToArrTokenIds[owner][i] == element) r = true;
if (r) ownerToArrTokenIds[owner][i] = ownerToArrTokenIds[owner][i + 1];
}
ownerToArrTokenIds[owner].pop();
}
function setStateForApes(uint[] memory ids, address sender, bytes1 newState) external override onlyAdmin {
for (uint i=0; i<ids.length; i++) {
require(idToStakeApe[ids[i]].state != newState, "This ape is already in this state ...");
require(idToStakeApe[ids[i]].owner == sender, "Must be the original owner of the ape");
idToStakeApe[ids[i]].state = newState;
idToStakeApe[ids[i]].stateDate = block.timestamp;
}
}
function stopStateForApe(uint id, address sender) external override onlyAdmin returns(uint) {
require(idToStakeApe[id].state != 'N', "This ape is doing nothing ...");
require(idToStakeApe[id].owner == sender, "Must be the original owner of the ape");
uint duration = (block.timestamp - idToStakeApe[id].stateDate) / 60;
idToStakeApe[id].state = 'N';
idToStakeApe[id].stateDate = 0;
console.log("End of training for %s", id);
return duration;
}
//
// Admin functions :
//
function getOwnerApes(address a) external view override returns(uint[] memory) {
return ownerToArrTokenIds[a];
}
function getApe(uint id) external view override returns(uint256,address,bytes1,uint256) {
return (idToStakeApe[id].tokenId, idToStakeApe[id].owner, idToStakeApe[id].state, idToStakeApe[id].stateDate);
}
function setApeState(uint id, bytes1 state, uint256 date) external override onlyAdmin {
idToStakeApe[id].state = state;
idToStakeApe[id].stateDate = date;
}
function transferApesBackToOwner() external override onlyAdmin {
for (uint i = 1; i < maxSupply; i++) {
if (idToStakeApe[i].owner != address(0)) {
address owner = idToStakeApe[i].owner;
delete idToStakeApe[i];
IERC721(apeAddress).transferFrom(
address(this),
owner,
i
);
}
}
}
function returnApeToOwner(uint256 tokenId) external override onlyAdmin {
if (idToStakeApe[tokenId].owner != address(0)) {
address owner = idToStakeApe[tokenId].owner;
delete idToStakeApe[tokenId];
IERC721(apeAddress).transferFrom(
address(this),
owner,
tokenId
);
}
}
function returnApeToAddress(uint256 tokenId, address owner) external override onlyAdmin {
delete idToStakeApe[tokenId];
// remove(ownerToArrTokenIds[owner], tokenId);
removeTokenToOwner(owner, tokenId);
IERC721(apeAddress).transferFrom(
address(this),
owner,
tokenId
);
}
// function transferApesToNewContract (address newContract) external onlyAdmin {
// //
// Address(this).transfer();
// }
function setClosed (bool c) public onlyAdmin {
closed = c;
}
function recreateMapping() public onlyAdmin {
// If not able to find owner, set to admin...
}
function setMaxSupply (uint m) public onlyAdmin {
maxSupply = m;
}
modifier onlyAdmin {
require(admins[msg.sender], "Only admins can call this");
_;
}
function setAdmin(address addr) public onlyAdmin {
admins[addr] = true;
}
function unsetAdmin(address addr) public onlyAdmin {
delete admins[addr];
}
function setContracts(address _ape, address _ball) external onlyAdmin {
apeAddress = _ape;
ballAddress = _ball;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable collectionSize;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
* `collectionSize_` refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
struct StakeApe {
uint256 tokenId;
address owner;
bytes1 state;
// N: NoOp, T: Training, M: Match,
// L: Available for rent, D: Rented
uint256 stateDate;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import "./StakeApe.sol";
interface IAgency {
/** Put Apes into agency. Will transfer 721 tokens to the agency in order to play.
*/
function putApesToAgency(uint[] memory ids, address owner) external;
/** Transfer back the Apes from the Agency to original owner's wallet.
*/
function getApesFromAgency(uint[] memory ids, address owner) external;
function setStateForApes(uint[] memory ids, address sender, bytes1 newState) external;
function stopStateForApe(uint id, address sender) external returns(uint);
function getApe(uint id) external view returns(uint256,address,bytes1,uint256);
function setApeState(uint id, bytes1 state, uint256 date) external;
function getOwnerApes(address a) external view returns(uint[] memory);
function transferApesBackToOwner() external;
function returnApeToOwner(uint256 tokenId) external;
function returnApeToAddress(uint256 tokenId, address owner) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
|
Transfers `tokenId` from `from` to `to`. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./ Clear approvals from the previous owner If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
|
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
| 4,005
|
/*
Capital Technologies & Research - Capital (CALL)
*/
pragma solidity ^0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
/// Total amount of tokens
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _amount) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function approve(address _spender, uint256 _amount) public returns (bool success);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
//balance in each address account
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _amount The amount to be transferred.
*/
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(_to != address(0));
require(balances[msg.sender] >= _amount && _amount > 0
&& balances[_to].add(_amount) > balances[_to]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _amount uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
require(_to != address(0));
require(balances[_from] >= _amount);
require(allowed[_from][msg.sender] >= _amount);
require(_amount > 0 && balances[_to].add(_amount) > balances[_to]);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _amount The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _amount) public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken, Ownable {
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 onlyOwner{
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
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
}
}
/**
* @title CAPITAL (CALL) Token
* @dev Token representing CALL.
*/
contract CALLToken is BurnableToken {
string public name;
string public symbol;
uint256 public totalSupply;
uint8 public decimals = 18 ;
/**
*@dev users sending ether to this contract will be reverted. Any ether sent to the contract will be sent back to the caller
*/
function () public payable {
revert();
}
/**
* @dev Constructor function to initialize the initial supply of token to the creator of the contract
* @param initialSupply The initial supply of tokens which will be fixed through out
* @param tokenName The name of the token
* @param tokenSymbol The symboll of the token
*/
function CALLToken(uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply.mul( 10 ** uint256(decimals));
name = tokenName;
symbol = tokenSymbol;
balances[msg.sender] = totalSupply;
//Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator
emit Transfer(address(0), msg.sender, totalSupply);
}
/**
*@dev helper method to get token details, name, symbol and totalSupply in one go
*/
function getTokenDetail() public view returns (string, string, uint256) {
return (name, symbol, totalSupply);
}
}
|
Constructor function to initialize the initial supply of token to the creator of the contract initialSupply The initial supply of tokens which will be fixed through out tokenName The name of the token tokenSymbol The symboll of the token/Emitting transfer event since assigning all tokens to the creator also corresponds to the transfer of tokens to the creator
|
function CALLToken(uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply.mul( 10 ** uint256(decimals));
name = tokenName;
symbol = tokenSymbol;
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
| 60,181
|
pragma solidity ^0.8.3;
import "./IPassify.sol";
// Needs to implement all functions of IPassify
contract Passify is IPassify {
constructor() IPassify() {}
uint _price = 0.29 ether; // $100, Sep 18, 2021
uint _stake = 0.0029 ether; // $1, Sep 18, 2021
struct Record {
uint8 min;
address[] custodians;
}
uint _numRecords;
mapping(uint => Record) private _records;
address[] private _custodians;
mapping(address => string) private _custodianURIs; // the link to custodian information (stored on IPFS)
/**
* @dev User calls this function when they register a new record. No fees paid.
*/
function addRecord(uint8 min, address[] memory custodians) external override {
uint recordId = _numRecords;
_records[recordId] = Record(min, custodians);
_numRecords++;
emit RecordAdded(msg.sender, recordId);
}
/**
* @dev User calls when they unregister their record. No fees paid.
*/
function removeRecord(uint256 recordId) external override {
require(_records[recordId].min != 0);
delete _records[recordId];
_numRecords--;
}
/**
* @dev User calls this function when they wish to unlock their password
* (after verifying their identity).
*
* Emits a {Pay} event
*/
function pay(uint256 recordId) external payable override {
uint numCustodians = _records[recordId].custodians.length;
require(msg.value > (_price * numCustodians));
emit Pay(msg.sender, recordId);
}
/**
* CURRENTLY UNIMPLEMENTED
* @dev User calls this function when they contend that custodians have not sent
* the correct information
*
* Emits a {Dispute} event
*/
function dispute(uint256 recordId, address custodian) external override{
emit Dispute(msg.sender, recordId, custodian);
}
/**
* @dev Custodian calls this function to register their service on our platform
* Requirement:
* msg.value >= fixed stake amount
*/
function stake(string calldata custodianURI) payable external override{
require(bytes(_custodianURIs[msg.sender]).length != 0 && msg.value > _stake);
_custodians.push(msg.sender);
_custodianURIs[msg.sender] = custodianURI;
}
/**
* @dev Returns all registered custodians.
*/
function getCustodians() external override view returns(address[] memory) {
return _custodians;
}
/**
* @dev Returns the URI that holds custodian information.
*/
function getCustodianURI(address custodian) external override view returns(string memory) {
return _custodianURIs[custodian];
}
function getRecord(uint256 recordId) external override view returns(uint8, address[] memory) {
return (_records[recordId].min, _records[recordId].custodians);
}
}
|
User calls this function when they wish to unlock their password (after verifying their identity). Emits a {Pay} event/
|
function pay(uint256 recordId) external payable override {
uint numCustodians = _records[recordId].custodians.length;
require(msg.value > (_price * numCustodians));
emit Pay(msg.sender, recordId);
}
| 1,801,581
|
./full_match/42/0x22056E4687Ed374921317bc9372b7b03daEC346d/sources/craft.sol
|
Need to cheeck possiblity to vaildate the tokenId;
|
function setCreatorFeeRate(uint256 tokenId, uint256 feeRate) external onlyOwner {
require( feeRate > 0, "CreatorFeeRateFeeRate should be grether than zero");
require(tokens[tokenId].creator != address(0), "Token with provided tokenId not available");
tokens[tokenId].creatorFeeRate = feeRate;
}
| 16,220,716
|
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
// Sources flattened with hardhat v2.8.4 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.5.0
// 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/token/ERC20/extensions/IERC20Metadata.sol@v4.5.0
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File @openzeppelin/contracts/utils/Context.sol@v4.5.0
// 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/token/ERC20/ERC20.sol@v4.5.0
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol@v4.5.0
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
}
// File @openzeppelin/contracts/security/Pausable.sol@v4.5.0
// 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/access/IAccessControl.sol@v4.5.0
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// File @openzeppelin/contracts/utils/Strings.sol@v4.5.0
// 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 @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.5.0
// 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 @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.5.0
// 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 @openzeppelin/contracts/access/AccessControl.sol@v4.5.0
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File contracts/Staking/Owned.sol
// https://docs.synthetix.io/contracts/Owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor (address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// File contracts/ERC20/ERC20PermissionedMint.sol
contract ERC20PermissionedMint is ERC20, ERC20Burnable, Owned {
// Core
address public timelock_address;
// Minters
address[] public minters_array; // Allowed to mint
mapping(address => bool) public minters; // Mapping is also used for faster verification
/* ========== CONSTRUCTOR ========== */
constructor(
address _creator_address,
address _timelock_address,
string memory _name,
string memory _symbol
)
ERC20(_name, _symbol)
Owned(_creator_address)
{
timelock_address = _timelock_address;
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyMinters() {
require(minters[msg.sender] == true, "Only minters");
_;
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Used by minters when user redeems
function minter_burn_from(address b_address, uint256 b_amount) public onlyMinters {
super.burnFrom(b_address, b_amount);
emit TokenMinterBurned(b_address, msg.sender, b_amount);
}
// This function is what other minters will call to mint new tokens
function minter_mint(address m_address, uint256 m_amount) public onlyMinters {
super._mint(m_address, m_amount);
emit TokenMinterMinted(msg.sender, m_address, m_amount);
}
// Adds whitelisted minters
function addMinter(address minter_address) public onlyByOwnGov {
require(minter_address != address(0), "Zero address detected");
require(minters[minter_address] == false, "Address already exists");
minters[minter_address] = true;
minters_array.push(minter_address);
emit MinterAdded(minter_address);
}
// Remove a minter
function removeMinter(address minter_address) public onlyByOwnGov {
require(minter_address != address(0), "Zero address detected");
require(minters[minter_address] == true, "Address nonexistant");
// Delete from the mapping
delete minters[minter_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < minters_array.length; i++){
if (minters_array[i] == minter_address) {
minters_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
emit MinterRemoved(minter_address);
}
/* ========== EVENTS ========== */
event TokenMinterBurned(address indexed from, address indexed to, uint256 amount);
event TokenMinterMinted(address indexed from, address indexed to, uint256 amount);
event MinterAdded(address minter_address);
event MinterRemoved(address minter_address);
}
// File contracts/FPI/FPI.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ================================ FPI ===============================
// ====================================================================
// Frax Price Index
// Initial peg target is the US CPI-U (Consumer Price Index, All Urban Consumers)
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Jack Corddry: https://github.com/corddry
// Reviewer(s) / Contributor(s)
// Sam Kazemian: https://github.com/samkazemian
// Rich Gee: https://github.com/zer0blockchain
// Dennis: https://github.com/denett
contract FPI is ERC20PermissionedMint {
/* ========== CONSTRUCTOR ========== */
constructor(
address _creator_address,
address _timelock_address
)
ERC20PermissionedMint(_creator_address, _timelock_address, "Frax Price Index", "FPI")
{
_mint(_creator_address, 100000000e18); // Genesis mint
}
}
// File contracts/Frax/IFrax.sol
interface IFrax {
function COLLATERAL_RATIO_PAUSER() external view returns (bytes32);
function DEFAULT_ADMIN_ADDRESS() external view returns (address);
function DEFAULT_ADMIN_ROLE() external view returns (bytes32);
function addPool(address pool_address ) external;
function allowance(address owner, address spender ) external view returns (uint256);
function approve(address spender, uint256 amount ) external returns (bool);
function balanceOf(address account ) external view returns (uint256);
function burn(uint256 amount ) external;
function burnFrom(address account, uint256 amount ) external;
function collateral_ratio_paused() external view returns (bool);
function controller_address() external view returns (address);
function creator_address() external view returns (address);
function decimals() external view returns (uint8);
function decreaseAllowance(address spender, uint256 subtractedValue ) external returns (bool);
function eth_usd_consumer_address() external view returns (address);
function eth_usd_price() external view returns (uint256);
function frax_eth_oracle_address() external view returns (address);
function frax_info() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256);
function frax_pools(address ) external view returns (bool);
function frax_pools_array(uint256 ) external view returns (address);
function frax_price() external view returns (uint256);
function frax_step() external view returns (uint256);
function fxs_address() external view returns (address);
function fxs_eth_oracle_address() external view returns (address);
function fxs_price() external view returns (uint256);
function genesis_supply() external view returns (uint256);
function getRoleAdmin(bytes32 role ) external view returns (bytes32);
function getRoleMember(bytes32 role, uint256 index ) external view returns (address);
function getRoleMemberCount(bytes32 role ) external view returns (uint256);
function globalCollateralValue() external view returns (uint256);
function global_collateral_ratio() external view returns (uint256);
function grantRole(bytes32 role, address account ) external;
function hasRole(bytes32 role, address account ) external view returns (bool);
function increaseAllowance(address spender, uint256 addedValue ) external returns (bool);
function last_call_time() external view returns (uint256);
function minting_fee() external view returns (uint256);
function name() external view returns (string memory);
function owner_address() external view returns (address);
function pool_burn_from(address b_address, uint256 b_amount ) external;
function pool_mint(address m_address, uint256 m_amount ) external;
function price_band() external view returns (uint256);
function price_target() external view returns (uint256);
function redemption_fee() external view returns (uint256);
function refreshCollateralRatio() external;
function refresh_cooldown() external view returns (uint256);
function removePool(address pool_address ) external;
function renounceRole(bytes32 role, address account ) external;
function revokeRole(bytes32 role, address account ) external;
function setController(address _controller_address ) external;
function setETHUSDOracle(address _eth_usd_consumer_address ) external;
function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address ) external;
function setFXSAddress(address _fxs_address ) external;
function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address ) external;
function setFraxStep(uint256 _new_step ) external;
function setMintingFee(uint256 min_fee ) external;
function setOwner(address _owner_address ) external;
function setPriceBand(uint256 _price_band ) external;
function setPriceTarget(uint256 _new_price_target ) external;
function setRedemptionFee(uint256 red_fee ) external;
function setRefreshCooldown(uint256 _new_cooldown ) external;
function setTimelock(address new_timelock ) external;
function symbol() external view returns (string memory);
function timelock_address() external view returns (address);
function toggleCollateralRatio() external;
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint256 amount ) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount ) external returns (bool);
function weth_address() external view returns (address);
}
// File contracts/Frax/IFraxAMOMinter.sol
// MAY need to be updated
interface IFraxAMOMinter {
function FRAX() external view returns(address);
function FXS() external view returns(address);
function acceptOwnership() external;
function addAMO(address amo_address, bool sync_too) external;
function allAMOAddresses() external view returns(address[] memory);
function allAMOsLength() external view returns(uint256);
function amos(address) external view returns(bool);
function amos_array(uint256) external view returns(address);
function burnFraxFromAMO(uint256 frax_amount) external;
function burnFxsFromAMO(uint256 fxs_amount) external;
function col_idx() external view returns(uint256);
function collatDollarBalance() external view returns(uint256);
function collatDollarBalanceStored() external view returns(uint256);
function collat_borrow_cap() external view returns(int256);
function collat_borrowed_balances(address) external view returns(int256);
function collat_borrowed_sum() external view returns(int256);
function collateral_address() external view returns(address);
function collateral_token() external view returns(address);
function correction_offsets_amos(address, uint256) external view returns(int256);
function custodian_address() external view returns(address);
function dollarBalances() external view returns(uint256 frax_val_e18, uint256 collat_val_e18);
// function execute(address _to, uint256 _value, bytes _data) external returns(bool, bytes);
function fraxDollarBalanceStored() external view returns(uint256);
function fraxTrackedAMO(address amo_address) external view returns(int256);
function fraxTrackedGlobal() external view returns(int256);
function frax_mint_balances(address) external view returns(int256);
function frax_mint_cap() external view returns(int256);
function frax_mint_sum() external view returns(int256);
function fxs_mint_balances(address) external view returns(int256);
function fxs_mint_cap() external view returns(int256);
function fxs_mint_sum() external view returns(int256);
function giveCollatToAMO(address destination_amo, uint256 collat_amount) external;
function min_cr() external view returns(uint256);
function mintFraxForAMO(address destination_amo, uint256 frax_amount) external;
function mintFxsForAMO(address destination_amo, uint256 fxs_amount) external;
function missing_decimals() external view returns(uint256);
function nominateNewOwner(address _owner) external;
function nominatedOwner() external view returns(address);
function oldPoolCollectAndGive(address destination_amo) external;
function oldPoolRedeem(uint256 frax_amount) external;
function old_pool() external view returns(address);
function owner() external view returns(address);
function pool() external view returns(address);
function receiveCollatFromAMO(uint256 usdc_amount) external;
function recoverERC20(address tokenAddress, uint256 tokenAmount) external;
function removeAMO(address amo_address, bool sync_too) external;
function setAMOCorrectionOffsets(address amo_address, int256 frax_e18_correction, int256 collat_e18_correction) external;
function setCollatBorrowCap(uint256 _collat_borrow_cap) external;
function setCustodian(address _custodian_address) external;
function setFraxMintCap(uint256 _frax_mint_cap) external;
function setFraxPool(address _pool_address) external;
function setFxsMintCap(uint256 _fxs_mint_cap) external;
function setMinimumCollateralRatio(uint256 _min_cr) external;
function setTimelock(address new_timelock) external;
function syncDollarBalances() external;
function timelock_address() external view returns(address);
}
// File contracts/Oracle/AggregatorV3Interface.sol
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File @chainlink/contracts/src/v0.8/vendor/BufferChainlink.sol@v0.4.0
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for writing to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library BufferChainlink {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint256 capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint256 capacity) internal pure returns (buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes memory b) internal pure returns (buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
function resize(buffer memory buf, uint256 capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint256 a, uint256 b) private pure returns (uint256) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Writes a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The start offset to write to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function write(
buffer memory buf,
uint256 off,
bytes memory data,
uint256 len
) internal pure returns (buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint256 dest;
uint256 src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
unchecked {
uint256 mask = (256**(32 - len)) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
return buf;
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(
buffer memory buf,
bytes memory data,
uint256 len
) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeUint8(
buffer memory buf,
uint256 off,
uint8 data
) internal pure returns (buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
/**
* @dev Appends a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns (buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
/**
* @dev Writes up to 32 bytes to the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function write(
buffer memory buf,
uint256 off,
bytes32 data,
uint256 len
) private pure returns (buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
unchecked {
uint256 mask = (256**len) - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
}
return buf;
}
/**
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeBytes20(
buffer memory buf,
uint256 off,
bytes20 data
) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
/**
* @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer, for chaining.
*/
function writeInt(
buffer memory buf,
uint256 off,
uint256 data,
uint256 len
) private pure returns (buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint256 mask = (256**len) - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + off + sizeof(buffer length) + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(
buffer memory buf,
uint256 data,
uint256 len
) internal pure returns (buffer memory) {
return writeInt(buf, buf.buf.length, data, len);
}
}
// File @chainlink/contracts/src/v0.8/vendor/CBORChainlink.sol@v0.4.0
library CBORChainlink {
using BufferChainlink for BufferChainlink.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_TAG = 6;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
uint8 private constant TAG_TYPE_BIGNUM = 2;
uint8 private constant TAG_TYPE_NEGATIVE_BIGNUM = 3;
function encodeFixedNumeric(BufferChainlink.buffer memory buf, uint8 major, uint64 value) private pure {
if(value <= 23) {
buf.appendUint8(uint8((major << 5) | value));
} else if (value <= 0xFF) {
buf.appendUint8(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if (value <= 0xFFFF) {
buf.appendUint8(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if (value <= 0xFFFFFFFF) {
buf.appendUint8(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else {
buf.appendUint8(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(BufferChainlink.buffer memory buf, uint8 major) private pure {
buf.appendUint8(uint8((major << 5) | 31));
}
function encodeUInt(BufferChainlink.buffer memory buf, uint value) internal pure {
if(value > 0xFFFFFFFFFFFFFFFF) {
encodeBigNum(buf, value);
} else {
encodeFixedNumeric(buf, MAJOR_TYPE_INT, uint64(value));
}
}
function encodeInt(BufferChainlink.buffer memory buf, int value) internal pure {
if(value < -0x10000000000000000) {
encodeSignedBigNum(buf, value);
} else if(value > 0xFFFFFFFFFFFFFFFF) {
encodeBigNum(buf, uint(value));
} else if(value >= 0) {
encodeFixedNumeric(buf, MAJOR_TYPE_INT, uint64(uint256(value)));
} else {
encodeFixedNumeric(buf, MAJOR_TYPE_NEGATIVE_INT, uint64(uint256(-1 - value)));
}
}
function encodeBytes(BufferChainlink.buffer memory buf, bytes memory value) internal pure {
encodeFixedNumeric(buf, MAJOR_TYPE_BYTES, uint64(value.length));
buf.append(value);
}
function encodeBigNum(BufferChainlink.buffer memory buf, uint value) internal pure {
buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_BIGNUM));
encodeBytes(buf, abi.encode(value));
}
function encodeSignedBigNum(BufferChainlink.buffer memory buf, int input) internal pure {
buf.appendUint8(uint8((MAJOR_TYPE_TAG << 5) | TAG_TYPE_NEGATIVE_BIGNUM));
encodeBytes(buf, abi.encode(uint256(-1 - input)));
}
function encodeString(BufferChainlink.buffer memory buf, string memory value) internal pure {
encodeFixedNumeric(buf, MAJOR_TYPE_STRING, uint64(bytes(value).length));
buf.append(bytes(value));
}
function startArray(BufferChainlink.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(BufferChainlink.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(BufferChainlink.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
// File @chainlink/contracts/src/v0.8/Chainlink.sol@v0.4.0
/**
* @title Library for common Chainlink functions
* @dev Uses imported CBOR library for encoding to buffer
*/
library Chainlink {
uint256 internal constant defaultBufferSize = 256; // solhint-disable-line const-name-snakecase
using CBORChainlink for BufferChainlink.buffer;
struct Request {
bytes32 id;
address callbackAddress;
bytes4 callbackFunctionId;
uint256 nonce;
BufferChainlink.buffer buf;
}
/**
* @notice Initializes a Chainlink request
* @dev Sets the ID, callback address, and callback function signature on the request
* @param self The uninitialized request
* @param jobId The Job Specification ID
* @param callbackAddr The callback address
* @param callbackFunc The callback function signature
* @return The initialized request
*/
function initialize(
Request memory self,
bytes32 jobId,
address callbackAddr,
bytes4 callbackFunc
) internal pure returns (Chainlink.Request memory) {
BufferChainlink.init(self.buf, defaultBufferSize);
self.id = jobId;
self.callbackAddress = callbackAddr;
self.callbackFunctionId = callbackFunc;
return self;
}
/**
* @notice Sets the data for the buffer without encoding CBOR on-chain
* @dev CBOR can be closed with curly-brackets {} or they can be left off
* @param self The initialized request
* @param data The CBOR data
*/
function setBuffer(Request memory self, bytes memory data) internal pure {
BufferChainlink.init(self.buf, data.length);
BufferChainlink.append(self.buf, data);
}
/**
* @notice Adds a string value to the request with a given key name
* @param self The initialized request
* @param key The name of the key
* @param value The string value to add
*/
function add(
Request memory self,
string memory key,
string memory value
) internal pure {
self.buf.encodeString(key);
self.buf.encodeString(value);
}
/**
* @notice Adds a bytes value to the request with a given key name
* @param self The initialized request
* @param key The name of the key
* @param value The bytes value to add
*/
function addBytes(
Request memory self,
string memory key,
bytes memory value
) internal pure {
self.buf.encodeString(key);
self.buf.encodeBytes(value);
}
/**
* @notice Adds a int256 value to the request with a given key name
* @param self The initialized request
* @param key The name of the key
* @param value The int256 value to add
*/
function addInt(
Request memory self,
string memory key,
int256 value
) internal pure {
self.buf.encodeString(key);
self.buf.encodeInt(value);
}
/**
* @notice Adds a uint256 value to the request with a given key name
* @param self The initialized request
* @param key The name of the key
* @param value The uint256 value to add
*/
function addUint(
Request memory self,
string memory key,
uint256 value
) internal pure {
self.buf.encodeString(key);
self.buf.encodeUInt(value);
}
/**
* @notice Adds an array of strings to the request with a given key name
* @param self The initialized request
* @param key The name of the key
* @param values The array of string values to add
*/
function addStringArray(
Request memory self,
string memory key,
string[] memory values
) internal pure {
self.buf.encodeString(key);
self.buf.startArray();
for (uint256 i = 0; i < values.length; i++) {
self.buf.encodeString(values[i]);
}
self.buf.endSequence();
}
}
// File @chainlink/contracts/src/v0.8/interfaces/ENSInterface.sol@v0.4.0
interface ENSInterface {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(
bytes32 node,
bytes32 label,
address owner
) external;
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
// File @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol@v0.4.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/interfaces/ChainlinkRequestInterface.sol@v0.4.0
interface ChainlinkRequestInterface {
function oracleRequest(
address sender,
uint256 requestPrice,
bytes32 serviceAgreementID,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 nonce,
uint256 dataVersion,
bytes calldata data
) external;
function cancelOracleRequest(
bytes32 requestId,
uint256 payment,
bytes4 callbackFunctionId,
uint256 expiration
) external;
}
// File @chainlink/contracts/src/v0.8/interfaces/OracleInterface.sol@v0.4.0
interface OracleInterface {
function fulfillOracleRequest(
bytes32 requestId,
uint256 payment,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 expiration,
bytes32 data
) external returns (bool);
function isAuthorizedSender(address node) external view returns (bool);
function withdraw(address recipient, uint256 amount) external;
function withdrawable() external view returns (uint256);
}
// File @chainlink/contracts/src/v0.8/interfaces/OperatorInterface.sol@v0.4.0
interface OperatorInterface is OracleInterface, ChainlinkRequestInterface {
function operatorRequest(
address sender,
uint256 payment,
bytes32 specId,
bytes4 callbackFunctionId,
uint256 nonce,
uint256 dataVersion,
bytes calldata data
) external;
function fulfillOracleRequest2(
bytes32 requestId,
uint256 payment,
address callbackAddress,
bytes4 callbackFunctionId,
uint256 expiration,
bytes calldata data
) external returns (bool);
function ownerTransferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function distributeFunds(address payable[] calldata receivers, uint256[] calldata amounts) external payable;
function getAuthorizedSenders() external returns (address[] memory);
function setAuthorizedSenders(address[] calldata senders) external;
function getForwarder() external returns (address);
}
// File @chainlink/contracts/src/v0.8/interfaces/PointerInterface.sol@v0.4.0
interface PointerInterface {
function getAddress() external view returns (address);
}
// File @chainlink/contracts/src/v0.8/vendor/ENSResolver.sol@v0.4.0
abstract contract ENSResolver_Chainlink {
function addr(bytes32 node) public view virtual returns (address);
}
// File @chainlink/contracts/src/v0.8/ChainlinkClient.sol@v0.4.0
/**
* @title The ChainlinkClient contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Chainlink network
*/
abstract contract ChainlinkClient {
using Chainlink for Chainlink.Request;
uint256 internal constant LINK_DIVISIBILITY = 10**18;
uint256 private constant AMOUNT_OVERRIDE = 0;
address private constant SENDER_OVERRIDE = address(0);
uint256 private constant ORACLE_ARGS_VERSION = 1;
uint256 private constant OPERATOR_ARGS_VERSION = 2;
bytes32 private constant ENS_TOKEN_SUBNAME = keccak256("link");
bytes32 private constant ENS_ORACLE_SUBNAME = keccak256("oracle");
address private constant LINK_TOKEN_POINTER = 0xC89bD4E1632D3A43CB03AAAd5262cbe4038Bc571;
ENSInterface private s_ens;
bytes32 private s_ensNode;
LinkTokenInterface private s_link;
OperatorInterface private s_oracle;
uint256 private s_requestCount = 1;
mapping(bytes32 => address) private s_pendingRequests;
event ChainlinkRequested(bytes32 indexed id);
event ChainlinkFulfilled(bytes32 indexed id);
event ChainlinkCancelled(bytes32 indexed id);
/**
* @notice Creates a request that can hold additional parameters
* @param specId The Job Specification ID that the request will be created for
* @param callbackAddr address to operate the callback on
* @param callbackFunctionSignature function signature to use for the callback
* @return A Chainlink Request struct in memory
*/
function buildChainlinkRequest(
bytes32 specId,
address callbackAddr,
bytes4 callbackFunctionSignature
) internal pure returns (Chainlink.Request memory) {
Chainlink.Request memory req;
return req.initialize(specId, callbackAddr, callbackFunctionSignature);
}
/**
* @notice Creates a request that can hold additional parameters
* @param specId The Job Specification ID that the request will be created for
* @param callbackFunctionSignature function signature to use for the callback
* @return A Chainlink Request struct in memory
*/
function buildOperatorRequest(bytes32 specId, bytes4 callbackFunctionSignature)
internal
view
returns (Chainlink.Request memory)
{
Chainlink.Request memory req;
return req.initialize(specId, address(this), callbackFunctionSignature);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev Calls `chainlinkRequestTo` with the stored oracle address
* @param req The initialized Chainlink Request
* @param payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendChainlinkRequest(Chainlink.Request memory req, uint256 payment) internal returns (bytes32) {
return sendChainlinkRequestTo(address(s_oracle), req, payment);
}
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param oracleAddress The address of the oracle for the request
* @param req The initialized Chainlink Request
* @param payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendChainlinkRequestTo(
address oracleAddress,
Chainlink.Request memory req,
uint256 payment
) internal returns (bytes32 requestId) {
uint256 nonce = s_requestCount;
s_requestCount = nonce + 1;
bytes memory encodedRequest = abi.encodeWithSelector(
ChainlinkRequestInterface.oracleRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
req.id,
address(this),
req.callbackFunctionId,
nonce,
ORACLE_ARGS_VERSION,
req.buf.buf
);
return _rawRequest(oracleAddress, nonce, payment, encodedRequest);
}
/**
* @notice Creates a Chainlink request to the stored oracle address
* @dev This function supports multi-word response
* @dev Calls `sendOperatorRequestTo` with the stored oracle address
* @param req The initialized Chainlink Request
* @param payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendOperatorRequest(Chainlink.Request memory req, uint256 payment) internal returns (bytes32) {
return sendOperatorRequestTo(address(s_oracle), req, payment);
}
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev This function supports multi-word response
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param oracleAddress The address of the oracle for the request
* @param req The initialized Chainlink Request
* @param payment The amount of LINK to send for the request
* @return requestId The request ID
*/
function sendOperatorRequestTo(
address oracleAddress,
Chainlink.Request memory req,
uint256 payment
) internal returns (bytes32 requestId) {
uint256 nonce = s_requestCount;
s_requestCount = nonce + 1;
bytes memory encodedRequest = abi.encodeWithSelector(
OperatorInterface.operatorRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // Amount value - overridden by onTokenTransfer by the actual amount of LINK sent
req.id,
req.callbackFunctionId,
nonce,
OPERATOR_ARGS_VERSION,
req.buf.buf
);
return _rawRequest(oracleAddress, nonce, payment, encodedRequest);
}
/**
* @notice Make a request to an oracle
* @param oracleAddress The address of the oracle for the request
* @param nonce used to generate the request ID
* @param payment The amount of LINK to send for the request
* @param encodedRequest data encoded for request type specific format
* @return requestId The request ID
*/
function _rawRequest(
address oracleAddress,
uint256 nonce,
uint256 payment,
bytes memory encodedRequest
) private returns (bytes32 requestId) {
requestId = keccak256(abi.encodePacked(this, nonce));
s_pendingRequests[requestId] = oracleAddress;
emit ChainlinkRequested(requestId);
require(s_link.transferAndCall(oracleAddress, payment, encodedRequest), "unable to transferAndCall to oracle");
}
/**
* @notice Allows a request to be cancelled if it has not been fulfilled
* @dev Requires keeping track of the expiration value emitted from the oracle contract.
* Deletes the request from the `pendingRequests` mapping.
* Emits ChainlinkCancelled event.
* @param requestId The request ID
* @param payment The amount of LINK sent for the request
* @param callbackFunc The callback function specified for the request
* @param expiration The time of the expiration for the request
*/
function cancelChainlinkRequest(
bytes32 requestId,
uint256 payment,
bytes4 callbackFunc,
uint256 expiration
) internal {
OperatorInterface requested = OperatorInterface(s_pendingRequests[requestId]);
delete s_pendingRequests[requestId];
emit ChainlinkCancelled(requestId);
requested.cancelOracleRequest(requestId, payment, callbackFunc, expiration);
}
/**
* @notice the next request count to be used in generating a nonce
* @dev starts at 1 in order to ensure consistent gas cost
* @return returns the next request count to be used in a nonce
*/
function getNextRequestCount() internal view returns (uint256) {
return s_requestCount;
}
/**
* @notice Sets the stored oracle address
* @param oracleAddress The address of the oracle contract
*/
function setChainlinkOracle(address oracleAddress) internal {
s_oracle = OperatorInterface(oracleAddress);
}
/**
* @notice Sets the LINK token address
* @param linkAddress The address of the LINK token contract
*/
function setChainlinkToken(address linkAddress) internal {
s_link = LinkTokenInterface(linkAddress);
}
/**
* @notice Sets the Chainlink token address for the public
* network as given by the Pointer contract
*/
function setPublicChainlinkToken() internal {
setChainlinkToken(PointerInterface(LINK_TOKEN_POINTER).getAddress());
}
/**
* @notice Retrieves the stored address of the LINK token
* @return The address of the LINK token
*/
function chainlinkTokenAddress() internal view returns (address) {
return address(s_link);
}
/**
* @notice Retrieves the stored address of the oracle contract
* @return The address of the oracle contract
*/
function chainlinkOracleAddress() internal view returns (address) {
return address(s_oracle);
}
/**
* @notice Allows for a request which was created on another contract to be fulfilled
* on this contract
* @param oracleAddress The address of the oracle contract that will fulfill the request
* @param requestId The request ID used for the response
*/
function addChainlinkExternalRequest(address oracleAddress, bytes32 requestId) internal notPendingRequest(requestId) {
s_pendingRequests[requestId] = oracleAddress;
}
/**
* @notice Sets the stored oracle and LINK token contracts with the addresses resolved by ENS
* @dev Accounts for subnodes having different resolvers
* @param ensAddress The address of the ENS contract
* @param node The ENS node hash
*/
function useChainlinkWithENS(address ensAddress, bytes32 node) internal {
s_ens = ENSInterface(ensAddress);
s_ensNode = node;
bytes32 linkSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_TOKEN_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(s_ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
/**
* @notice Sets the stored oracle contract with the address resolved by ENS
* @dev This may be called on its own as long as `useChainlinkWithENS` has been called previously
*/
function updateChainlinkOracleWithENS() internal {
bytes32 oracleSubnode = keccak256(abi.encodePacked(s_ensNode, ENS_ORACLE_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(s_ens.resolver(oracleSubnode));
setChainlinkOracle(resolver.addr(oracleSubnode));
}
/**
* @notice Ensures that the fulfillment is valid for this contract
* @dev Use if the contract developer prefers methods instead of modifiers for validation
* @param requestId The request ID for fulfillment
*/
function validateChainlinkCallback(bytes32 requestId)
internal
recordChainlinkFulfillment(requestId)
// solhint-disable-next-line no-empty-blocks
{
}
/**
* @dev Reverts if the sender is not the oracle of the request.
* Emits ChainlinkFulfilled event.
* @param requestId The request ID for fulfillment
*/
modifier recordChainlinkFulfillment(bytes32 requestId) {
require(msg.sender == s_pendingRequests[requestId], "Source must be the oracle of the request");
delete s_pendingRequests[requestId];
emit ChainlinkFulfilled(requestId);
_;
}
/**
* @dev Reverts if the request is already pending
* @param requestId The request ID for fulfillment
*/
modifier notPendingRequest(bytes32 requestId) {
require(s_pendingRequests[requestId] == address(0), "Request is already pending");
_;
}
}
// File contracts/Math/BokkyPooBahsDateTimeLibrary.sol
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
(uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
(uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
(year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
(,month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
(,,day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
(uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
(uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
// File contracts/Math/BokkyPooBahsDateTimeContract.sol
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.00 - Contract Instance
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018.
//
// GNU Lesser General Public License 3.0
// https://www.gnu.org/licenses/lgpl-3.0.en.html
// ----------------------------------------------------------------------------
contract BokkyPooBahsDateTimeContract {
uint public constant SECONDS_PER_DAY = 24 * 60 * 60;
uint public constant SECONDS_PER_HOUR = 60 * 60;
uint public constant SECONDS_PER_MINUTE = 60;
int public constant OFFSET19700101 = 2440588;
uint public constant DOW_MON = 1;
uint public constant DOW_TUE = 2;
uint public constant DOW_WED = 3;
uint public constant DOW_THU = 4;
uint public constant DOW_FRI = 5;
uint public constant DOW_SAT = 6;
uint public constant DOW_SUN = 7;
function _now() public view returns (uint timestamp) {
timestamp = block.timestamp;
}
function _nowDateTime() public view returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day, hour, minute, second) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(block.timestamp);
}
function _daysFromDate(uint year, uint month, uint day) public pure returns (uint _days) {
return BokkyPooBahsDateTimeLibrary._daysFromDate(year, month, day);
}
function _daysToDate(uint _days) public pure returns (uint year, uint month, uint day) {
return BokkyPooBahsDateTimeLibrary._daysToDate(_days);
}
function timestampFromDate(uint year, uint month, uint day) public pure returns (uint timestamp) {
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, month, day);
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) public pure returns (uint timestamp) {
return BokkyPooBahsDateTimeLibrary.timestampFromDateTime(year, month, day, hour, minute, second);
}
function timestampToDate(uint timestamp) public pure returns (uint year, uint month, uint day) {
(year, month, day) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
}
function timestampToDateTime(uint timestamp) public pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day, hour, minute, second) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(timestamp);
}
function isValidDate(uint year, uint month, uint day) public pure returns (bool valid) {
valid = BokkyPooBahsDateTimeLibrary.isValidDate(year, month, day);
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) public pure returns (bool valid) {
valid = BokkyPooBahsDateTimeLibrary.isValidDateTime(year, month, day, hour, minute, second);
}
function isLeapYear(uint timestamp) public pure returns (bool leapYear) {
leapYear = BokkyPooBahsDateTimeLibrary.isLeapYear(timestamp);
}
function _isLeapYear(uint year) public pure returns (bool leapYear) {
leapYear = BokkyPooBahsDateTimeLibrary._isLeapYear(year);
}
function isWeekDay(uint timestamp) public pure returns (bool weekDay) {
weekDay = BokkyPooBahsDateTimeLibrary.isWeekDay(timestamp);
}
function isWeekEnd(uint timestamp) public pure returns (bool weekEnd) {
weekEnd = BokkyPooBahsDateTimeLibrary.isWeekEnd(timestamp);
}
function getDaysInMonth(uint timestamp) public pure returns (uint daysInMonth) {
daysInMonth = BokkyPooBahsDateTimeLibrary.getDaysInMonth(timestamp);
}
function _getDaysInMonth(uint year, uint month) public pure returns (uint daysInMonth) {
daysInMonth = BokkyPooBahsDateTimeLibrary._getDaysInMonth(year, month);
}
function getDayOfWeek(uint timestamp) public pure returns (uint dayOfWeek) {
dayOfWeek = BokkyPooBahsDateTimeLibrary.getDayOfWeek(timestamp);
}
function getYear(uint timestamp) public pure returns (uint year) {
year = BokkyPooBahsDateTimeLibrary.getYear(timestamp);
}
function getMonth(uint timestamp) public pure returns (uint month) {
month = BokkyPooBahsDateTimeLibrary.getMonth(timestamp);
}
function getDay(uint timestamp) public pure returns (uint day) {
day = BokkyPooBahsDateTimeLibrary.getDay(timestamp);
}
function getHour(uint timestamp) public pure returns (uint hour) {
hour = BokkyPooBahsDateTimeLibrary.getHour(timestamp);
}
function getMinute(uint timestamp) public pure returns (uint minute) {
minute = BokkyPooBahsDateTimeLibrary.getMinute(timestamp);
}
function getSecond(uint timestamp) public pure returns (uint second) {
second = BokkyPooBahsDateTimeLibrary.getSecond(timestamp);
}
function addYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addYears(timestamp, _years);
}
function addMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addMonths(timestamp, _months);
}
function addDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addDays(timestamp, _days);
}
function addHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addHours(timestamp, _hours);
}
function addMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addMinutes(timestamp, _minutes);
}
function addSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.addSeconds(timestamp, _seconds);
}
function subYears(uint timestamp, uint _years) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subYears(timestamp, _years);
}
function subMonths(uint timestamp, uint _months) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subMonths(timestamp, _months);
}
function subDays(uint timestamp, uint _days) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subDays(timestamp, _days);
}
function subHours(uint timestamp, uint _hours) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subHours(timestamp, _hours);
}
function subMinutes(uint timestamp, uint _minutes) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subMinutes(timestamp, _minutes);
}
function subSeconds(uint timestamp, uint _seconds) public pure returns (uint newTimestamp) {
newTimestamp = BokkyPooBahsDateTimeLibrary.subSeconds(timestamp, _seconds);
}
function diffYears(uint fromTimestamp, uint toTimestamp) public pure returns (uint _years) {
_years = BokkyPooBahsDateTimeLibrary.diffYears(fromTimestamp, toTimestamp);
}
function diffMonths(uint fromTimestamp, uint toTimestamp) public pure returns (uint _months) {
_months = BokkyPooBahsDateTimeLibrary.diffMonths(fromTimestamp, toTimestamp);
}
function diffDays(uint fromTimestamp, uint toTimestamp) public pure returns (uint _days) {
_days = BokkyPooBahsDateTimeLibrary.diffDays(fromTimestamp, toTimestamp);
}
function diffHours(uint fromTimestamp, uint toTimestamp) public pure returns (uint _hours) {
_hours = BokkyPooBahsDateTimeLibrary.diffHours(fromTimestamp, toTimestamp);
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) public pure returns (uint _minutes) {
_minutes = BokkyPooBahsDateTimeLibrary.diffMinutes(fromTimestamp, toTimestamp);
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) public pure returns (uint _seconds) {
_seconds = BokkyPooBahsDateTimeLibrary.diffSeconds(fromTimestamp, toTimestamp);
}
}
// File contracts/Uniswap/TransferHelper.sol
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File contracts/Oracle/CPITrackerOracle.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= CPITrackerOracle =========================
// ====================================================================
// Pull in CPI data and track it in Dec 2021 dollars
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Sam Kazemian: https://github.com/samkazemian
// Rich Gee: https://github.com/zer0blockchain
// Dennis: https://github.com/denett
// References
// https://docs.chain.link/docs/make-a-http-get-request/#api-consumer-example
contract CPITrackerOracle is Owned, ChainlinkClient {
using Chainlink for Chainlink.Request;
// Core
BokkyPooBahsDateTimeContract public time_contract;
address public timelock_address;
address public bot_address;
// Data
uint256 public cpi_last = 28012600000; // Dec 2021 CPI-U, 280.126 * 100000000
uint256 public cpi_target = 28193300000; // Jan 2022 CPI-U, 281.933 * 100000000
uint256 public peg_price_last = 1e18; // Use currPegPrice(). Will always be in Dec 2021 dollars
uint256 public peg_price_target = 1006450668627688968; // Will always be in Dec 2021 dollars
// Chainlink
address public oracle; // Chainlink CPI oracle address
bytes32 public jobId; // Job ID for the CPI-U date
uint256 public fee; // LINK token fee
// Tracking
uint256 public stored_year = 2022; // Last time (year) the stored CPI data was updated
uint256 public stored_month = 1; // Last time (month) the stored CPI data was updated
uint256 public lastUpdateTime = 1644886800; // Last time the stored CPI data was updated.
uint256 public ramp_period = 28 * 86400; // Apply the CPI delta to the peg price over a set period
uint256 public future_ramp_period = 28 * 86400;
CPIObservation[] public cpi_observations; // Historical tracking of CPI data
// Safety
uint256 public max_delta_frac = 25000; // 2.5%. Max month-to-month CPI delta.
// Misc
string[13] public month_names; // English names of the 12 months
uint256 public fulfill_ready_day = 15; // Date of the month that CPI data is expected to by ready by
/* ========== STRUCTS ========== */
struct CPIObservation {
uint256 result_year;
uint256 result_month;
uint256 cpi_target;
uint256 peg_price_target;
uint256 timestamp;
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock");
_;
}
modifier onlyByOwnGovBot() {
require(msg.sender == owner || msg.sender == timelock_address || msg.sender == bot_address, "Not owner, tlck, or bot");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _creator_address,
address _timelock_address
) Owned(_creator_address) {
timelock_address = _timelock_address;
// Initialize the array. Cannot be done in the declaration
month_names = [
'',
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
// CPI [Ethereum]
// =================================
// setPublicChainlinkToken();
// time_contract = BokkyPooBahsDateTimeContract(0x90503D86E120B3B309CEBf00C2CA013aB3624736);
// oracle = 0x049Bd8C3adC3fE7d3Fc2a44541d955A537c2A484;
// jobId = "1c309d42c7084b34b1acf1a89e7b51fc";
// fee = 50e18; // 50 LINK
// CPI [Polygon Mainnet]
// =================================
// setChainlinkToken(0x53E0bca35eC356BD5ddDFebbD1Fc0fD03FaBad39);
// time_contract = BokkyPooBahsDateTimeContract(0x998da4fCB229Db1AA84395ef6f0c6be6Ef3dbE58);
// oracle = 0x9B44870bcc35734c08e40F847cC068c0bA618194;
// jobId = "8107f18343a24980b2fe7d3c8f32630f";
// fee = 1e17; // 0.1 LINK
// CPI [Polygon Mumbai]
// =================================
setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB);
time_contract = BokkyPooBahsDateTimeContract(0x2Dd1B4D4548aCCeA497050619965f91f78b3b532);
oracle = 0x3c30c5c415B2410326297F0f65f5Cbb32f3aefCc;
jobId = "32c3e7b12fe44665a4e2bb87aa9779af";
fee = 1e17; // 0.1 LINK
// Add the first observation
cpi_observations.push(CPIObservation(
2021,
12,
cpi_last,
peg_price_last,
1642208400 // Dec data observed on Jan 15 2021
));
// Add the second observation
cpi_observations.push(CPIObservation(
2022,
1,
cpi_target,
peg_price_target,
1644886800 // Jan data observed on Feb 15 2022
));
}
/* ========== VIEWS ========== */
function upcomingCPIParams() public view returns (
uint256 upcoming_year,
uint256 upcoming_month,
uint256 upcoming_timestamp
) {
if (stored_month == 12) {
upcoming_year = stored_year + 1;
upcoming_month = 1;
}
else {
upcoming_year = stored_year;
upcoming_month = stored_month + 1;
}
// Data is usually released by the 15th day of the next month (fulfill_ready_day)
// https://www.usinflationcalculator.com/inflation/consumer-price-index-release-schedule/
upcoming_timestamp = time_contract.timestampFromDate(upcoming_year, upcoming_month, fulfill_ready_day);
}
// Display the upcoming CPI month
function upcomingSerie() external view returns (string memory serie_name) {
// Get the upcoming CPI params
(uint256 upcoming_year, uint256 upcoming_month, ) = upcomingCPIParams();
// Convert to a string
return string(abi.encodePacked("CUSR0000SA0", " ", month_names[upcoming_month], " ", Strings.toString(upcoming_year)));
}
// Delta between the current and previous peg prices
function currDeltaFracE6() public view returns (int256) {
return int256(((peg_price_target - peg_price_last) * 1e6) / peg_price_last);
}
// Absolute value of the delta between the current and previous peg prices
function currDeltaFracAbsE6() public view returns (uint256) {
int256 curr_delta_frac = currDeltaFracE6();
if (curr_delta_frac > 0) return uint256(curr_delta_frac);
else return uint256(-curr_delta_frac);
}
// Current peg price in E18, accounting for the ramping
function currPegPrice() external view returns (uint256) {
uint256 elapsed_time = block.timestamp - lastUpdateTime;
if (elapsed_time >= ramp_period) {
return peg_price_target;
}
else {
// Calculate the fraction of the delta to use, based on the elapsed time
// Can be negative in case of deflation (that never happens right :])
int256 fractional_price_delta = (int256(peg_price_target - peg_price_last) * int256(elapsed_time)) / int256(ramp_period);
return uint256(int256(peg_price_last) + int256(fractional_price_delta));
}
}
/* ========== MUTATIVE ========== */
// Fetch the CPI data from the Chainlink oracle
function requestCPIData() external onlyByOwnGovBot returns (bytes32 requestId)
{
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
// Get the upcoming CPI params
(uint256 upcoming_year, uint256 upcoming_month, uint256 upcoming_timestamp) = upcomingCPIParams();
// Don't update too fast
require(block.timestamp >= upcoming_timestamp, "Too early");
request.add("serie", "CUSR0000SA0"); // CPI-U: https://data.bls.gov/timeseries/CUSR0000SA0
request.add("month", month_names[upcoming_month]);
request.add("year", Strings.toString(upcoming_year));
return sendChainlinkRequestTo(oracle, request, fee);
}
/**
* Callback function
*/
// Called by the Chainlink oracle
function fulfill(bytes32 _requestId, uint256 result) public recordChainlinkFulfillment(_requestId)
{
// Set the stored CPI and price to the old targets
cpi_last = cpi_target;
peg_price_last = peg_price_target;
// Set the target CPI and price based on the results
cpi_target = result;
peg_price_target = (peg_price_last * cpi_target) / cpi_last;
// Make sure the delta isn't too large
require(currDeltaFracAbsE6() <= max_delta_frac, "Delta too high");
// Update the timestamp
lastUpdateTime = block.timestamp;
// Update the year and month
(uint256 result_year, uint256 result_month, ) = upcomingCPIParams();
stored_year = result_year;
stored_month = result_month;
// Update the future ramp period, if applicable
// A ramp cannot be updated mid-month as it will mess up the last_price math;
ramp_period = future_ramp_period;
// Add the observation
cpi_observations.push(CPIObservation(
result_year,
result_month,
cpi_target,
peg_price_target,
block.timestamp
));
emit CPIUpdated(result_year, result_month, result, peg_price_target, ramp_period);
}
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunc,
uint256 _expiration
) external onlyByOwnGovBot {
cancelChainlinkRequest(_requestId, _payment, _callbackFunc, _expiration);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setTimelock(address _new_timelock_address) external onlyByOwnGov {
timelock_address = _new_timelock_address;
}
function setBot(address _new_bot_address) external onlyByOwnGov {
bot_address = _new_bot_address;
}
function setOracleInfo(address _oracle, bytes32 _jobId, uint256 _fee) external onlyByOwnGov {
oracle = _oracle;
jobId = _jobId;
fee = _fee;
}
function setMaxDeltaFrac(uint256 _max_delta_frac) external onlyByOwnGov {
max_delta_frac = _max_delta_frac;
}
function setFulfillReadyDay(uint256 _fulfill_ready_day) external onlyByOwnGov {
fulfill_ready_day = _fulfill_ready_day;
}
function setFutureRampPeriod(uint256 _future_ramp_period) external onlyByOwnGov {
future_ramp_period = _future_ramp_period; // In sec
}
// Mainly for recovering LINK
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
// Only the owner address can ever receive the recovery withdrawal
TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount);
}
/* ========== EVENTS ========== */
event CPIUpdated(uint256 year, uint256 month, uint256 result, uint256 peg_price_target, uint256 ramp_period);
}
// File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniswapV2PairV5.sol
interface IUniswapV2PairV5 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniV2TWAMMPair.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= IUniV2TWAMMPair ==========================
// ====================================================================
// TWAMM LP Pair Interface
// Inspired by https://www.paradigm.xyz/2021/07/twamm
// https://github.com/para-dave/twamm
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Rich Gee: https://github.com/zer0blockchain
// Dennis: https://github.com/denett
// Reviewer(s) / Contributor(s)
// Travis Moore: https://github.com/FortisFortuna
// Sam Kazemian: https://github.com/samkazemian
interface IUniV2TWAMMPair is IUniswapV2PairV5 {
// TWAMM
event LongTermSwap0To1(address indexed addr, uint256 orderId, uint256 amount0In, uint256 numberOfTimeIntervals);
event LongTermSwap1To0(address indexed addr, uint256 orderId, uint256 amount1In, uint256 numberOfTimeIntervals);
event CancelLongTermOrder(address indexed addr, uint256 orderId, address sellToken, uint256 unsoldAmount, address buyToken, uint256 purchasedAmount);
event WithdrawProceedsFromLongTermOrder(address indexed addr, uint256 orderId, address indexed proceedToken, uint256 proceeds, bool orderExpired);
function longTermSwapFrom0To1(uint256 amount0In, uint256 numberOfTimeIntervals) external returns (uint256 orderId);
function longTermSwapFrom1To0(uint256 amount1In, uint256 numberOfTimeIntervals) external returns (uint256 orderId);
function cancelLongTermSwap(uint256 orderId) external;
function withdrawProceedsFromLongTermSwap(uint256 orderId) external returns (bool is_expired);
function executeVirtualOrders(uint256 blockTimestamp) external;
function orderTimeInterval() external returns (uint256);
function getTWAPHistoryLength() external view returns (uint);
function getTwammReserves() external view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast, uint112 _twammReserve0, uint112 _twammReserve1);
function getReserveAfterTwamm(uint256 blockTimestamp) external view returns (uint112 _reserve0, uint112 _reserve1, uint256 lastVirtualOrderTimestamp, uint112 _twammReserve0, uint112 _twammReserve1);
function getNextOrderID() external view returns (uint256);
function getOrderIDsForUser(address user) external view returns (uint256[] memory);
function getOrderIDsForUserLength(address user) external view returns (uint256);
// function getDetailedOrdersForUser(address user, uint256 offset, uint256 limit) external view returns (LongTermOrdersLib.Order[] memory detailed_orders);
function twammUpToDate() external view returns (bool);
function getTwammState() external view returns (uint256 token0Rate, uint256 token1Rate, uint256 lastVirtualOrderTimestamp, uint256 orderTimeInterval_rtn, uint256 rewardFactorPool0, uint256 rewardFactorPool1);
function getTwammSalesRateEnding(uint256 _blockTimestamp) external view returns (uint256 orderPool0SalesRateEnding, uint256 orderPool1SalesRateEnding);
function getTwammRewardFactor(uint256 _blockTimestamp) external view returns (uint256 rewardFactorPool0AtTimestamp, uint256 rewardFactorPool1AtTimestamp);
function getTwammOrder(uint256 orderId) external view returns (uint256 id, uint256 expirationTimestamp, uint256 saleRate, address owner, address sellTokenAddr, address buyTokenAddr);
function getTwammOrderProceeds(uint256 orderId, uint256 blockTimestamp) external view returns (bool orderExpired, uint256 totalReward);
function togglePauseNewSwaps() external;
}
// File contracts/Uniswap_V2_TWAMM/core/interfaces/IUniswapV2FactoryV5.sol
interface IUniswapV2FactoryV5 {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File contracts/Uniswap_V2_TWAMM/libraries/Babylonian.sol
// 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);
}
}
// File contracts/Uniswap_V2_TWAMM/libraries/FullMath.sol
/// @notice Math library that facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision.
/// @author Adapted from https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/FullMath.sol.
/// @dev Handles "phantom overflow", i.e., allows multiplication and division where an intermediate value overflows 256 bits.
library FullMath {
/// @notice Calculates floor(aรbรทdenominator) with full precision - throws if result overflows an uint256 or denominator == 0.
/// @param a The multiplicand.
/// @param b The multiplier.
/// @param denominator The divisor.
/// @return result The 256-bit result.
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b.
// Compute the product mod 2**256 and mod 2**256 - 1,
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0.
uint256 prod0; // Least significant 256 bits of the product.
uint256 prod1; // Most significant 256 bits of the product.
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256 -
// also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0] -
// compute remainder using mulmod.
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number.
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator -
// compute largest power of two divisor of denominator
// (always >= 1).
uint256 twos = uint256(-int256(denominator)) & denominator;
// Divide denominator by power of two.
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two.
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos -
// if twos is zero, then it becomes one.
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256 -
// now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// for four bits. That is, denominator * inv = 1 mod 2**4.
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // Inverse mod 2**8.
inv *= 2 - denominator * inv; // Inverse mod 2**16.
inv *= 2 - denominator * inv; // Inverse mod 2**32.
inv *= 2 - denominator * inv; // Inverse mod 2**64.
inv *= 2 - denominator * inv; // Inverse mod 2**128.
inv *= 2 - denominator * inv; // Inverse mod 2**256.
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(aรbรทdenominator) with full precision - throws if result overflows an uint256 or denominator == 0.
/// @param a The multiplicand.
/// @param b The multiplier.
/// @param denominator The divisor.
/// @return result The 256-bit result.
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
unchecked {
if (mulmod(a, b, denominator) != 0) {
require(result < type(uint256).max);
result++;
}
}
}
}
// File contracts/Uniswap_V2_TWAMM/periphery/libraries/UniswapV2LiquidityMathLibraryMini.sol
// library containing some math for dealing with the liquidity shares of a pair, e.g. computing their exact value
// in terms of the underlying tokens
library UniswapV2LiquidityMathLibraryMini {
// computes the direction and magnitude of the profit-maximizing trade
// function computeProfitMaximizingTrade(
// uint256 truePriceTokenA,
// uint256 truePriceTokenB,
// uint256 reserveA,
// uint256 reserveB
// ) pure internal returns (uint256 amountIn) {
// bool aToB = ((reserveA * truePriceTokenB) / reserveB) < truePriceTokenA;
// uint256 invariant = reserveA * reserveB;
// // true price is expressed as a ratio, so both values must be non-zero
// require(truePriceTokenA != 0 && truePriceTokenB != 0, "CPMT: ZERO_PRICE");
// uint256 leftSide = Babylonian.sqrt(
// FullMath.mulDiv(
// (invariant * 1000),
// aToB ? truePriceTokenA : truePriceTokenB,
// (aToB ? truePriceTokenB : truePriceTokenA) * 997
// )
// );
// uint256 rightSide = (aToB ? reserveA * 1000 : reserveB * 1000) / 997;
// if (leftSide < rightSide) return (0);
// // compute the amount that must be sent to move the price to the profit-maximizing price
// amountIn = leftSide - rightSide;
// }
function computeProfitMaximizingTrade(
uint256 inTokenTruePrice,
uint256 outTokenTruePrice,
uint256 reserveIn,
uint256 reserveOut
) pure internal returns (uint256 amountIn) {
uint256 invariant = reserveIn * reserveOut;
// true price is expressed as a ratio, so both values must be non-zero
require(inTokenTruePrice != 0 && outTokenTruePrice != 0, "CPMT: ZERO_PRICE");
uint256 leftSide = Babylonian.sqrt(
FullMath.mulDiv(
(invariant * 1000),
inTokenTruePrice,
outTokenTruePrice * 997
)
);
uint256 rightSide = (reserveIn * 1000) / 997;
if (leftSide < rightSide) return (0);
// compute the amount that must be sent to move the price to the profit-maximizing price
amountIn = leftSide - rightSide;
}
}
// File contracts/FPI/FPIControllerPool.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================= FPIControllerPool =========================
// ====================================================================
// Makes sure FPI is targeting the CPI peg
// First method is minting / redeeming with FRAX
// Second is bulk TWAMM trades
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Sam Kazemian: https://github.com/samkazemian
// Rich Gee: https://github.com/zer0blockchain
// Dennis: https://github.com/denett
// Jack Corddry: https://github.com/corddry
contract FPIControllerPool is Owned {
// Core
address public timelock_address;
FPI public FPI_TKN;
IFrax public FRAX;
IUniV2TWAMMPair public TWAMM;
// Oracles
AggregatorV3Interface public priceFeedFRAXUSD;
AggregatorV3Interface public priceFeedFPIUSD;
uint256 public chainlink_frax_usd_decimals;
uint256 public chainlink_fpi_usd_decimals;
CPITrackerOracle public cpiTracker;
// Tracking
uint256 public last_order_id_twamm; // Last TWAMM order ID that was used
// AMO addresses (lend out FRAX)
address[] public amos_array;
mapping(address => bool) public amos; // Mapping is also used for faster verification
// FRAX borrowed balances
mapping(address => int256) public frax_borrowed_balances; // Amount of FRAX the contract borrowed, by AMO
int256 public frax_borrowed_sum = 0; // Across all AMOs
int256 public frax_borrow_cap = int256(10000000e18); // Max amount of FRAX the contract can borrow from this contract
// Mint Fee Related
bool public use_manual_mint_fee = true;
uint256 public mint_fee_manual = 3000; // E6
uint256 public mint_fee_multiplier = 1000000; // E6
// Redeem Fee Related
bool public use_manual_redeem_fee = true;
uint256 public redeem_fee_manual = 3000; // E6
uint256 public redeem_fee_multiplier = 1000000; // E6
// Safety
uint256 public fpi_mint_cap = 110000000e18; // 110M
uint256 public peg_band_mint_redeem = 50000; // 5%
uint256 public peg_band_twamm = 100000; // 10%
uint256 public max_swap_frax_amt_in = 10000000e18; // 10M, mainly fat-finger precautions
uint256 public max_swap_fpi_amt_in = 10000000e18; // 10M, mainly fat-finger precautions
bool public mints_paused = false;
bool public redeems_paused = false;
// Constants for various precisions
uint256 public constant PRICE_PRECISION = 1e18;
uint256 public constant FEE_PRECISION = 1e6;
uint256 public constant PEG_BAND_PRECISION = 1e6;
// Misc
bool public frax_is_token0;
bool public pending_twamm_order = false;
uint256 public num_twamm_intervals = 168; // Each interval is default 3600 sec (1 hr)
uint256 public swap_period = 7 * 86400; // 7 days
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock");
_;
}
modifier validAMO(address amo_address) {
require(amos[amo_address], "Invalid AMO");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _creator_address,
address _timelock_address,
address[6] memory _address_pack
) Owned(_creator_address) {
timelock_address = _timelock_address;
// Set instances
FRAX = IFrax(_address_pack[0]);
FPI_TKN = FPI(_address_pack[1]);
TWAMM = IUniV2TWAMMPair(_address_pack[2]);
priceFeedFRAXUSD = AggregatorV3Interface(_address_pack[3]);
priceFeedFPIUSD = AggregatorV3Interface(_address_pack[4]);
cpiTracker = CPITrackerOracle(_address_pack[5]);
// Set the oracle decimals
chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals();
chainlink_fpi_usd_decimals = priceFeedFPIUSD.decimals();
// Need to know which token FRAX is (0 or 1)
address token0 = TWAMM.token0();
if (token0 == address(FRAX)) frax_is_token0 = true;
else frax_is_token0 = false;
// Get the number of TWAMM intervals. Truncation desired
num_twamm_intervals = swap_period / TWAMM.orderTimeInterval();
}
/* ========== VIEWS ========== */
// Needed as a FRAX AMO
function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) {
frax_val_e18 = FRAX.balanceOf(address(this));
collat_val_e18 = (frax_val_e18 * 1e6) / FRAX.global_collateral_ratio();
}
// In Chainlink decimals
function getFRAXPriceE18() public view returns (uint256) {
(uint80 roundID, int price, , uint256 updatedAt, uint80 answeredInRound) = priceFeedFRAXUSD.latestRoundData();
require(price >= 0 && updatedAt!= 0 && answeredInRound >= roundID, "Invalid chainlink price");
return ((uint256(price) * 1e18) / (10 ** chainlink_frax_usd_decimals));
}
// In Chainlink decimals
function getFPIPriceE18() public view returns (uint256) {
(uint80 roundID, int price, , uint256 updatedAt, uint80 answeredInRound) = priceFeedFPIUSD.latestRoundData();
require(price >= 0 && updatedAt!= 0 && answeredInRound >= roundID, "Invalid chainlink price");
return ((uint256(price) * 1e18) / (10 ** chainlink_fpi_usd_decimals));
}
// Reserve spot price (fpi_price is dangerous / flash loan susceptible, so use carefully)
function getReservesAndFPISpot() public returns (uint256 reserveFRAX, uint256 reserveFPI, uint256 fpi_price) {
// Update and get the reserves
TWAMM.executeVirtualOrders(block.timestamp);
{
(uint256 reserveA, uint256 reserveB, ) = TWAMM.getReserves();
if (frax_is_token0){
reserveFRAX = reserveA;
reserveFPI = reserveB;
}
else {
reserveFRAX = reserveB;
reserveFPI = reserveA;
}
}
// Get the TWAMM reserve spot price
fpi_price = (reserveFRAX * 1e18) / reserveFPI;
}
// function getTwammToPegAmt() public returns (uint256 frax_in, uint256 fpi_in) {
// // Update and get the reserves
// (uint256 reserveFRAX, uint256 reserveFPI, uint256 reservePriceFPI) = getReservesAndFPISpot();
// // Get the CPI price
// uint256 cpi_peg_price = cpiTracker.currPegPrice();
// // Sort the pricing. NOTE: IN RATIOS, NOT PRICE
// uint256 truePriceFRAX = 1e18;
// uint256 truePriceFPI = cpi_peg_price;
// // Determine the direction
// if (fpi_to_frax) {
// return UniswapV2LiquidityMathLibraryMini.computeProfitMaximizingTrade(
// truePriceFPI, truePriceFRAX,
// reserveFPI, reserveFRAX
// );
// }
// else {
// return UniswapV2LiquidityMathLibraryMini.computeProfitMaximizingTrade(
// truePriceFRAX, truePriceFPI,
// reserveFRAX, reserveFPI
// );
// }
// }
// In E6
function mint_fee() public view returns (uint256 fee) {
if (use_manual_mint_fee) fee = mint_fee_manual;
else {
// For future variable fees
fee = 0;
// Apply the multiplier
fee = (fee * mint_fee_multiplier) / 1e6;
}
}
// In E6
function redeem_fee() public view returns (uint256 fee) {
if (use_manual_redeem_fee) fee = redeem_fee_manual;
else {
// For future variable fees
fee = 0;
// Apply the multiplier
fee = (fee * redeem_fee_multiplier) / 1e6;
}
}
// Get some info about the peg status
function pegStatusMntRdm() public view returns (uint256 cpi_peg_price, uint256 diff_frac_abs, bool within_range) {
uint256 fpi_price = getFPIPriceE18();
cpi_peg_price = cpiTracker.currPegPrice();
if (fpi_price > cpi_peg_price){
diff_frac_abs = ((fpi_price - cpi_peg_price) * PEG_BAND_PRECISION) / fpi_price;
}
else {
diff_frac_abs = ((cpi_peg_price - fpi_price) * PEG_BAND_PRECISION) / fpi_price;
}
within_range = (diff_frac_abs <= peg_band_mint_redeem);
}
// Get additional info about the peg status
function price_info() public view returns (
int256 collat_imbalance,
uint256 cpi_peg_price,
uint256 fpi_price,
uint256 price_diff_frac_abs
) {
fpi_price = getFPIPriceE18();
cpi_peg_price = cpiTracker.currPegPrice();
uint256 fpi_supply = FPI_TKN.totalSupply();
if (fpi_price > cpi_peg_price){
collat_imbalance = int256(((fpi_price - cpi_peg_price) * fpi_supply) / PRICE_PRECISION);
price_diff_frac_abs = ((fpi_price - cpi_peg_price) * PEG_BAND_PRECISION) / fpi_price;
}
else {
collat_imbalance = -1 * int256(((cpi_peg_price - fpi_price) * fpi_supply) / PRICE_PRECISION);
price_diff_frac_abs = ((cpi_peg_price - fpi_price) * PEG_BAND_PRECISION) / fpi_price;
}
}
/* ========== MUTATIVE ========== */
// Calculate Mint FPI with FRAX
function calcMintFPI(uint256 frax_in, uint256 min_fpi_out) public view returns (uint256 fpi_out) {
require(!mints_paused, "Mints paused");
// Fetch the CPI price and other info
(uint256 cpi_peg_price, , bool within_range) = pegStatusMntRdm();
// Make sure the peg is within range for minting
// Helps combat oracle errors and megadumping
require(within_range, "Peg band [Mint]");
// Calculate the amount of FPI that the incoming FRAX should give
fpi_out = (frax_in * PRICE_PRECISION) / cpi_peg_price;
// Apply the fee
fpi_out -= (fpi_out * mint_fee()) / FEE_PRECISION;
// Make sure enough FPI is generated
require(fpi_out >= min_fpi_out, "Slippage [Mint]");
// Check the mint cap
require(FPI_TKN.totalSupply() + fpi_out <= fpi_mint_cap, "FPI mint cap");
}
// Mint FPI with FRAX
function mintFPI(uint256 frax_in, uint256 min_fpi_out) external returns (uint256 fpi_out) {
fpi_out = calcMintFPI(frax_in, min_fpi_out);
// Pull in the FRAX
TransferHelper.safeTransferFrom(address(FRAX), msg.sender, address(this), frax_in);
// Mint FPI to the sender
FPI_TKN.minter_mint(msg.sender, fpi_out);
emit FPIMinted(frax_in, fpi_out);
}
// Calculate Redeem FPI for FRAX
function calcRedeemFPI(uint256 fpi_in, uint256 min_frax_out) public view returns (uint256 frax_out) {
require(!redeems_paused, "Redeems paused");
// Fetch the CPI price and other info
(uint256 cpi_peg_price, , bool within_range) = pegStatusMntRdm();
// Make sure the peg is within range for minting
// Helps combat oracle errors and megadumping
require(within_range, "Peg band [Redeem]");
// Calculate the amount of FRAX that the incoming FPI should give
frax_out = (fpi_in * cpi_peg_price) / PRICE_PRECISION;
// Apply the fee
frax_out -= (frax_out * redeem_fee()) / FEE_PRECISION;
// Make sure enough FRAX is generated
require(frax_out >= min_frax_out, "Slippage [Redeem]");
}
// Redeem FPI for FRAX
function redeemFPI(uint256 fpi_in, uint256 min_frax_out) external returns (uint256 frax_out) {
frax_out = calcRedeemFPI(fpi_in, min_frax_out);
// Pull in the FPI
TransferHelper.safeTransferFrom(address(FPI_TKN), msg.sender, address(this), fpi_in);
// Give FRAX to the sender
TransferHelper.safeTransfer(address(FRAX), msg.sender, frax_out);
emit FPIRedeemed(fpi_in, frax_out);
}
// Use the TWAMM for bulk peg corrections
function twammManual(uint256 frax_sell_amt, uint256 fpi_sell_amt, uint256 override_intervals) external onlyByOwnGov returns (uint256 frax_to_use, uint256 fpi_to_use) {
// Make sure only one direction occurs
require(!((frax_sell_amt > 0) && (fpi_sell_amt > 0)), "Can only sell in one direction");
// Update and get the reserves
// longTermSwapFrom0to1 and longTermSwapFrom1To0 do it automatically
// TWAMM.executeVirtualOrders(block.timestamp);
// Cancel the previous order (if any) and collect any leftover tokens
if (pending_twamm_order) TWAMM.cancelLongTermSwap(last_order_id_twamm);
// Now calculate the imbalance after the burn
(, , , uint256 price_diff_abs) = price_info();
// Make sure the FPI oracle price hasn't moved away too much from the target peg price
require(price_diff_abs <= peg_band_twamm, "Peg band [TWAMM]");
// Create a new order
last_order_id_twamm = TWAMM.getNextOrderID();
{
if (fpi_sell_amt > 0) {
// Mint FPI and sell for FRAX
// --------------------------------
fpi_to_use = fpi_sell_amt;
// Make sure nonzero
require(fpi_to_use > 0, "FPI sold must be nonzero");
// Safety check
require(fpi_to_use <= max_swap_fpi_amt_in, "Too much FPI sold");
// Mint some FPI
FPI_TKN.minter_mint(address(this), fpi_to_use);
// Approve FPI first
FPI_TKN.approve(address(TWAMM), fpi_to_use);
// Sell FPI for FRAX
if (frax_is_token0) {
TWAMM.longTermSwapFrom1To0(fpi_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals);
}
else {
TWAMM.longTermSwapFrom0To1(fpi_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals);
}
}
else {
// Use FRAX to buy FPI
// --------------------------------
frax_to_use = frax_sell_amt;
// Make sure nonzero
require(frax_to_use > 0, "FRAX sold must be nonzero");
// Safety check
require(frax_to_use <= max_swap_frax_amt_in, "Too much FRAX sold");
// Approve FRAX first
FRAX.approve(address(TWAMM), frax_to_use);
// Sell FRAX for FPI
if (frax_is_token0) {
TWAMM.longTermSwapFrom0To1(frax_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals);
}
else {
TWAMM.longTermSwapFrom1To0(frax_to_use, override_intervals > 0 ? override_intervals : num_twamm_intervals);
}
}
}
// Mark that there is a pending order
pending_twamm_order = true;
emit TWAMMedToPeg(last_order_id_twamm, frax_to_use, fpi_to_use, block.timestamp);
}
function cancelCurrTWAMMOrder(uint256 order_id_override) public onlyByOwnGov {
// Cancel the order
TWAMM.cancelLongTermSwap(order_id_override == 0 ? last_order_id_twamm : order_id_override);
// Clear the pending order indicator
pending_twamm_order = false;
}
function collectCurrTWAMMProceeds(uint256 order_id_override) external onlyByOwnGov {
// Withdraw current proceeds
bool is_expired = TWAMM.withdrawProceedsFromLongTermSwap(order_id_override == 0 ? last_order_id_twamm : order_id_override);
// If using the last_order_id_twamm and it is expired, clear the pending order indicator
if (is_expired && (order_id_override == 0)) pending_twamm_order = false;
}
/* ========== Burns and givebacks ========== */
// Burn unneeded or excess FPI.
function burnFPI(bool burn_all, uint256 fpi_amount) public onlyByOwnGov {
if (burn_all) {
// Burn any leftover FPI
FPI_TKN.burn(FPI_TKN.balanceOf(address(this)));
}
else FPI_TKN.burn(fpi_amount);
}
// ------------------------------------------------------------------
// ------------------------------ FRAX ------------------------------
// ------------------------------------------------------------------
// Lend the FRAX collateral to an AMO
function giveFRAXToAMO(address destination_amo, uint256 frax_amount) external onlyByOwnGov validAMO(destination_amo) {
int256 frax_amount_i256 = int256(frax_amount);
// Update the balances first
require((frax_borrowed_sum + frax_amount_i256) <= frax_borrow_cap, "Borrow cap");
frax_borrowed_balances[destination_amo] += frax_amount_i256;
frax_borrowed_sum += frax_amount_i256;
// Give the FRAX to the AMO
TransferHelper.safeTransfer(address(FRAX), destination_amo, frax_amount);
}
// AMO gives back FRAX. Needed for proper accounting
function receiveFRAXFromAMO(uint256 frax_amount) external validAMO(msg.sender) {
int256 frax_amt_i256 = int256(frax_amount);
// Give back first
TransferHelper.safeTransferFrom(address(FRAX), msg.sender, address(this), frax_amount);
// Then update the balances
frax_borrowed_balances[msg.sender] -= frax_amt_i256;
frax_borrowed_sum -= frax_amt_i256;
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Adds an AMO
function addAMO(address amo_address) public onlyByOwnGov {
require(amo_address != address(0), "Zero address detected");
require(amos[amo_address] == false, "Address already exists");
amos[amo_address] = true;
amos_array.push(amo_address);
emit AMOAdded(amo_address);
}
// Removes an AMO
function removeAMO(address amo_address) public onlyByOwnGov {
require(amo_address != address(0), "Zero address detected");
require(amos[amo_address] == true, "Address nonexistant");
// Delete from the mapping
delete amos[amo_address];
// 'Delete' from the array by setting the address to 0x0
for (uint i = 0; i < amos_array.length; i++){
if (amos_array[i] == amo_address) {
amos_array[i] = address(0); // This will leave a null in the array and keep the indices the same
break;
}
}
emit AMORemoved(amo_address);
}
function setOracles(address _frax_oracle, address _fpi_oracle, address _cpi_oracle) external onlyByOwnGov {
priceFeedFRAXUSD = AggregatorV3Interface(_frax_oracle);
priceFeedFPIUSD = AggregatorV3Interface(_fpi_oracle);
cpiTracker = CPITrackerOracle(_cpi_oracle);
// Set the Chainlink oracle decimals
chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals();
chainlink_fpi_usd_decimals = priceFeedFPIUSD.decimals();
}
function setTWAMMAndSwapPeriod(address _twamm_addr, uint256 _swap_period) external onlyByOwnGov {
// Cancel an outstanding order, if present
if (pending_twamm_order) cancelCurrTWAMMOrder(last_order_id_twamm);
// Change the TWAMM parameters
TWAMM = IUniV2TWAMMPair(_twamm_addr);
swap_period = _swap_period;
num_twamm_intervals = _swap_period / TWAMM.orderTimeInterval();
}
function toggleMints() external onlyByOwnGov {
mints_paused = !mints_paused;
}
function toggleRedeems() external onlyByOwnGov {
redeems_paused = !redeems_paused;
}
function setFraxBorrowCap(int256 _frax_borrow_cap) external onlyByOwnGov {
frax_borrow_cap = _frax_borrow_cap;
}
function setMintCap(uint256 _fpi_mint_cap) external onlyByOwnGov {
fpi_mint_cap = _fpi_mint_cap;
}
function setPegBands(uint256 _peg_band_mint_redeem, uint256 _peg_band_twamm) external onlyByOwnGov {
peg_band_mint_redeem = _peg_band_mint_redeem;
peg_band_twamm = _peg_band_twamm;
}
function setMintRedeemFees(
bool _use_manual_mint_fee,
uint256 _mint_fee_manual,
uint256 _mint_fee_multiplier,
bool _use_manual_redeem_fee,
uint256 _redeem_fee_manual,
uint256 _redeem_fee_multiplier
) external onlyByOwnGov {
use_manual_mint_fee = _use_manual_mint_fee;
mint_fee_manual = _mint_fee_manual;
mint_fee_multiplier = _mint_fee_multiplier;
use_manual_redeem_fee = _use_manual_redeem_fee;
redeem_fee_manual = _redeem_fee_manual;
redeem_fee_multiplier = _redeem_fee_multiplier;
}
function setTWAMMMaxSwapIn(uint256 _max_swap_frax_amt_in, uint256 _max_swap_fpi_amt_in) external onlyByOwnGov {
max_swap_frax_amt_in = _max_swap_frax_amt_in;
max_swap_fpi_amt_in = _max_swap_fpi_amt_in;
}
function setTimelock(address _new_timelock_address) external onlyByOwnGov {
timelock_address = _new_timelock_address;
}
// Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
// Only the owner address can ever receive the recovery withdrawal
TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount);
emit RecoveredERC20(tokenAddress, tokenAmount);
}
/* ========== EVENTS ========== */
event AMOAdded(address amo_address);
event AMORemoved(address amo_address);
event RecoveredERC20(address token, uint256 amount);
event FPIMinted(uint256 frax_in, uint256 fpi_out);
event FPIRedeemed(uint256 fpi_in, uint256 frax_out);
event TWAMMedToPeg(uint256 order_id, uint256 frax_amt, uint256 fpi_amt, uint256 timestamp);
}
|
Appends a byte to the buffer. Resizes if doing so would exceed the capacity of the buffer. buf The buffer to append to. data The data to append. return The original buffer, for chaining./
|
function appendUint8(buffer memory buf, uint8 data) internal pure returns (buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
| 1,301,047
|
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IERC20 {
function TOTALSUPPLY15() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF165(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER42(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE912(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE113(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM313(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER502(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL286(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: contracts/P2pSwap.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
contract P2pSwap {
struct Swap {
address aliceAddress;
address token1;
uint256 value1;
address token2;
uint256 value2;
uint8 executed; // 0 - pending, 1 - executed, 2 - cancelled
}
mapping(uint256 => Swap) swaps;
function GETSWAP929(uint256 _id) //inject NONSTANDARD NAMING
public view returns (address, address, uint256, address, uint256, uint8) {
Swap memory swap = swaps[_id];
return (
swap.aliceAddress,
swap.token1,
swap.value1,
swap.token2,
swap.value2,
swap.executed
);
}
function REGISTERSWAP626( //inject NONSTANDARD NAMING
uint256 _id,
address _aliceAddress,
address _token1,
uint256 _value1,
address _token2,
uint256 _value2)
public returns (bool) {
require(_id != 0);
require(_aliceAddress != address(0));
require(_token1 != address(0));
require(_value1 != 0);
require(_token2 != address(0));
require(_value2 != 0);
Swap storage swap = swaps[_id];
require(swap.aliceAddress == address(0), "Swap already exists");
swap.aliceAddress = _aliceAddress;
swap.token1 = _token1;
swap.value1 = _value1;
swap.token2 = _token2;
swap.value2 = _value2;
return true;
}
function CANCELSWAP640(uint256 _id) public returns (bool) { //inject NONSTANDARD NAMING
Swap storage swap = swaps[_id];
require(swap.executed == 0, "Swap not available");
swap.executed = 2;
}
function EXECUTESWAP306(uint256 _id, address _bob) //inject NONSTANDARD NAMING
public returns (bool) {
require(_bob != address(0));
Swap storage swap = swaps[_id];
require(swap.aliceAddress != address(0), "Swap does not exists");
require(swap.executed == 2, "Swap not available");
IERC20 Token1 = IERC20(swap.token1);
IERC20 Token2 = IERC20(swap.token2);
// Swap. Make sure to set the allowances in advance
Token1.TRANSFERFROM313(swap.aliceAddress, _bob, swap.value1);
Token2.TRANSFERFROM313(_bob, swap.aliceAddress, swap.value2);
swap.executed = 1;
return true;
}
}
|
inject NONSTANDARD NAMING
|
function TRANSFER42(address recipient, uint256 amount) external returns (bool);
| 6,449,025
|
pragma solidity 0.4.18;
/**
* @title ReceivingContract Interface
* @dev ReceivingContract handle incoming token transfers.
*/
contract ReceivingContract {
/**
* @dev Handle incoming token transfers.
* @param _from The token sender address.
* @param _value The amount of tokens.
*/
function tokenFallback(address _from, uint _value) public;
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint _a, uint _b)
internal
pure
returns (uint)
{
if (_a == 0) {
return 0;
}
uint c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint _a, uint _b)
internal
pure
returns (uint)
{
// Solidity automatically throws when dividing by 0
uint c = _a / _b;
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint _a, uint _b)
internal
pure
returns (uint)
{
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint _a, uint _b)
internal
pure
returns (uint)
{
uint c = _a + _b;
assert(c >= _a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* Events
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Constructor
* Sets the original `owner` of the contract to the sender account.
*/
function Ownable() public {
owner = msg.sender;
OwnershipTransferred(0, owner);
}
/**
* @dev Allows the current owner to transfer control of the contract to a new owner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner)
public
onlyOwner
{
require(_newOwner != 0);
OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Standard ERC20 token
*/
contract StandardToken is Ownable {
using SafeMath for uint;
string public name;
string public symbol;
uint8 public decimals;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) internal allowed;
/**
* Events
*/
event ChangeTokenInformation(string name, string symbol);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
/**
* Owner can update token information here.
*
* It is often useful to conceal the actual token association, until
* the token operations, like central issuance or reissuance have been completed.
*
* This function allows the token owner to rename the token after the operations
* have been completed and then point the audience to use the token contract.
*/
function changeTokenInformation(string _name, string _symbol)
public
onlyOwner
{
name = _name;
symbol = _symbol;
ChangeTokenInformation(_name, _symbol);
}
/**
* @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, uint _value)
public
returns (bool)
{
require(_to != 0);
require(_value > 0);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint _value)
public
returns (bool)
{
require(_to != 0);
require(_value > 0);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_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, uint _value)
public
returns (bool)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
*
* @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)
{
require(_addedValue > 0);
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)
*
* @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)
{
require(_subtractedValue > 0);
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;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return A uint specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint)
{
return allowed[_owner][_spender];
}
}
/**
* @title Pausable token
* @dev Token that can be freeze "Transfer" function
*/
contract PausableToken is StandardToken {
bool public isTradable = true;
/**
* Events
*/
event FreezeTransfer();
event UnfreezeTransfer();
modifier canTransfer() {
require(isTradable);
_;
}
/**
* Disallow to transfer token from an address to other address
*/
function freezeTransfer()
public
onlyOwner
{
isTradable = false;
FreezeTransfer();
}
/**
* Allow to transfer token from an address to other address
*/
function unfreezeTransfer()
public
onlyOwner
{
isTradable = true;
UnfreezeTransfer();
}
/**
* @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, uint _value)
public
canTransfer
returns (bool)
{
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint _value)
public
canTransfer
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
/**
* @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, uint _value)
public
canTransfer
returns (bool)
{
return super.approve(_spender, _value);
}
/**
* @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)
*
* @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
canTransfer
returns (bool)
{
return super.increaseApproval(_spender, _addedValue);
}
/**
* @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)
*
* @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
canTransfer
returns (bool)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title UpgradeAgent Interface
* @dev Upgrade agent transfers tokens to a new contract. Upgrade agent itself can be the
* token contract, or just a middle man contract doing the heavy lifting.
*/
contract UpgradeAgent {
bool public isUpgradeAgent = true;
function upgradeFrom(address _from, uint _value) public;
}
/**
* @title Upgradable token
*/
contract UpgradableToken is StandardToken {
address public upgradeMaster;
// The next contract where the tokens will be migrated.
UpgradeAgent public upgradeAgent;
bool public isUpgradable = false;
// How many tokens we have upgraded by now.
uint public totalUpgraded;
/**
* Events
*/
event ChangeUpgradeMaster(address newMaster);
event ChangeUpgradeAgent(address newAgent);
event FreezeUpgrade();
event UnfreezeUpgrade();
event Upgrade(address indexed from, address indexed to, uint value);
modifier onlyUpgradeMaster() {
require(msg.sender == upgradeMaster);
_;
}
modifier canUpgrade() {
require(isUpgradable);
_;
}
/**
* Change the upgrade master.
* @param _newMaster New upgrade master.
*/
function changeUpgradeMaster(address _newMaster)
public
onlyOwner
{
require(_newMaster != 0);
upgradeMaster = _newMaster;
ChangeUpgradeMaster(_newMaster);
}
/**
* Change the upgrade agent.
* @param _newAgent New upgrade agent.
*/
function changeUpgradeAgent(address _newAgent)
public
onlyOwner
{
require(totalUpgraded == 0);
upgradeAgent = UpgradeAgent(_newAgent);
require(upgradeAgent.isUpgradeAgent());
ChangeUpgradeAgent(_newAgent);
}
/**
* Disallow to upgrade token to new smart contract
*/
function freezeUpgrade()
public
onlyOwner
{
isUpgradable = false;
FreezeUpgrade();
}
/**
* Allow to upgrade token to new smart contract
*/
function unfreezeUpgrade()
public
onlyOwner
{
isUpgradable = true;
UnfreezeUpgrade();
}
/**
* Token holder upgrade their tokens to a new smart contract.
*/
function upgrade()
public
canUpgrade
{
uint amount = balanceOf[msg.sender];
require(amount > 0);
processUpgrade(msg.sender, amount);
}
/**
* Upgrader upgrade tokens of holder to a new smart contract.
* @param _holders List of token holder.
*/
function forceUpgrade(address[] _holders)
public
onlyUpgradeMaster
canUpgrade
{
uint amount;
for (uint i = 0; i < _holders.length; i++) {
amount = balanceOf[_holders[i]];
if (amount == 0) {
continue;
}
processUpgrade(_holders[i], amount);
}
}
function processUpgrade(address _holder, uint _amount)
private
{
balanceOf[_holder] = balanceOf[_holder].sub(_amount);
// Take tokens out from circulation
totalSupply = totalSupply.sub(_amount);
totalUpgraded = totalUpgraded.add(_amount);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(_holder, _amount);
Upgrade(_holder, upgradeAgent, _amount);
}
}
/**
* @title QNTU 1.0 token
*/
contract QNTU is UpgradableToken, PausableToken {
/**
* @dev Constructor
*/
function QNTU(address[] _wallets, uint[] _amount)
public
{
require(_wallets.length == _amount.length);
symbol = "QNTU";
name = "QNTU Token";
decimals = 18;
uint num = 0;
uint length = _wallets.length;
uint multiplier = 10 ** uint(decimals);
for (uint i = 0; i < length; i++) {
num = _amount[i] * multiplier;
balanceOf[_wallets[i]] = num;
Transfer(0, _wallets[i], num);
totalSupply += num;
}
}
/**
* @dev Transfer token for a specified contract
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transferToContract(address _to, uint _value)
public
canTransfer
returns (bool)
{
require(_value > 0);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
ReceivingContract receiver = ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value);
Transfer(msg.sender, _to, _value);
return true;
}
}
|
Change the upgrade master. _newMaster New upgrade master./
|
function changeUpgradeMaster(address _newMaster)
public
onlyOwner
{
require(_newMaster != 0);
upgradeMaster = _newMaster;
ChangeUpgradeMaster(_newMaster);
}
| 10,708,875
|
./partial_match/1/0xaCCaaDc4F8448F5f6C6aAf1c639Ec4B8bD1A8aF4/sources/contracts/extensions/NFT/components/BaseNFT.sol
|
Set NFT metadata base URI. URI must include the trailing slash./
|
function setBaseURI(string memory _baseUri, bool _reveal) external onlyRole(REVEALER_ROLE) {
if (isRevealed && !_reveal) {
revert ALREADY_REVEALED();
}
baseUri = _baseUri;
isRevealed = _reveal;
}
| 2,702,206
|
./full_match/44787/0xFcc63A90ca15Cab1da57daaC7F41eA2252e626E8/sources/contracts/StarNFT.sol
|
See {IERC721-allWithdrawal}./
|
function allWithdrawal(address owner) public {
uint256 _amount = 0;
for (uint256 i = 0 ; i < _balances[owner]; i ++) {
uint256 _tokenId = _ownedTokens[owner][i];
ibonus.setBonusWithdrawn(_amount);
ibonus.setTokenWithdraw(_tokenId,_amount);
_amount += ibonus.getBonus(_tokenId);
}
emit Test(owner,_amount);
starToken.transfer(owner, _amount);
}
| 13,283,297
|
// File: EpigeonInterfaces.sol
pragma solidity ^0.4.11;
//----------------------------------------------------------------------------------------------------
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 IERC777 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function granularity() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function send(address recipient, uint256 amount, bytes data) external;
function burn(uint256 amount, bytes data) external;
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
function authorizeOperator(address operator) external;
function revokeOperator(address operator) external;
function defaultOperators() external view returns (address[] memory);
function operatorSend(address sender, address recipient, uint256 amount, bytes data, bytes operatorData) external;
function operatorBurn(address account, uint256 amount, bytes data, bytes operatorData) external;
event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
//----------------------------------------------------------------------------------------------------
interface ILockable {
function lock(address to, uint256 amount, bytes32 hash) external;
function operatorLock(address from, address to, uint256 amount, bytes32 hash, bytes data, bytes operatorData) external;
function unlock(string unlockerPhrase) external;
function operatorUnlock(address to, string unlockerPhrase, bytes data, bytes operatorData) external;
function reclaim(address to, string unlockerPhrase) external;
function operatorReclaim(address from, address to, string unlockerPhrase, bytes data, bytes operatorData) external;
function unlockByLockedCoinContract(address to, bytes32 hash) external;
function reclaimByLockedCoinContract(address from, address to, bytes32 hash) external;
function lockedSupply() external view returns (uint256 locked_supply);
function lockedAmount(address from, bytes32 hash) external view returns (uint256 amount);
function lockedBalanceOf(address account) external view returns (uint256);
}
//----------------------------------------------------------------------------------------------------
interface IPigeonFactory {
function createCryptoPigeon(address to) external returns (ICryptoPigeon pigeonAddress);
function iAmFactory() external pure returns (bool);
function amIEpigeon() external returns (bool);
function factoryId() external view returns (uint256 id);
function getMetaDataForPigeon(address pigeon) external view returns (string metadata);
function mintingPrice() external view returns (uint256 price);
function totalSupply() external view returns (uint256 supply);
function maxSupply() external view returns (uint256 supply);
function getFactoryTokenPrice(address ERC20Token) external view returns (uint256 price);
}
//----------------------------------------------------------------------------------------------------
interface ICryptoPigeon {
function burnPigeon() external;
function iAmPigeon() external pure returns (bool);
function transferPigeon(address newOwner) external;
function hasFlown() external view returns (bool);
function toAddress() external view returns (address addressee);
function owner() external view returns (address ownerAddress);
function manager() external view returns (address managerAddress);
function factoryId() external view returns (uint256 id);
}
//----------------------------------------------------------------------------------------------------
interface IEpigeon {
function pigeonDestinations() external view returns (IPigeonDestinationDirectory destinations);
function nameAndKeyDirectory() external view returns (INameAndPublicKeyDirectory directory);
function getLastFactoryId() external view returns (uint256 id);
function getFactoryAddresstoId(uint256 id) external view returns (address factoryAddress);
function getPigeonPriceForFactory(uint256 factoryId) external view returns (uint256 price);
function getPigeonTokenPriceForFactory(address ERC20Token, uint256 factoryId) external view returns (uint256 price);
function createCryptoPigeonNFT(address to, uint256 factoryId) external returns (address pigeonaddress);
function transferPigeon(address from, address to, address pigeon) external;
function burnPigeon(address pigeon) external;
function nftContractAddress() external view returns (address nftContract);
function validPigeon(address pigeon, address pigeonOwner) external view returns (bool);
}
//----------------------------------------------------------------------------------------------------
interface IEpigeonNFT {
function isTokenizedPigeon(address pigeon) external view returns (bool);
}
//----------------------------------------------------------------------------------------------------
interface INameAndPublicKeyDirectory {
function getPublicKeyForAddress (address owner) external view returns (string key);
function getUserNameForAddress (address owner) external view returns (string name);
}
//----------------------------------------------------------------------------------------------------
interface IPigeonDestinationDirectory{
function changeToAddress(address newToAddress, address oldToAddress) external;
function setToAddress(address newToAddress) external;
function deleteToAddress(address oldToAddress) external;
function deleteToAddressByEpigeon(address pigeon) external;
function pigeonsSentToAddressLenght(address toAddress) external view returns (uint256 length);
function pigeonSentToAddressByIndex(address toAddress, uint index) external view returns (address pigeonAddress);
}
//----------------------------------------------------------------------------------------------------
interface IPigeonManagerDirectory{
function changeManager(address newManager, address oldManager) external;
function deleteManager(address oldManager) external;
function setManager(address newManager) external;
function pigeonsOfManagerLenght(address toAddress) external view returns (uint256 length);
function pigeonOfManagerByIndex(address toAddress, uint index) external view returns (address pigeonAddress);
}
//----------------------------------------------------------------------------------------------------
// File: Epigeon.sol
pragma solidity ^0.4.11;
//----------------------------------------------------------------------------------------------------
contract NameAndPublicKeyDirectory is INameAndPublicKeyDirectory{
mapping (address => string) internal addressToPublicKey;
mapping (address => string) internal addressToUserName;
mapping (string => address) internal userNameToAddress;
Epigeon epigeonAddress;
uint256 public uniqueNamePrice;
constructor (){
epigeonAddress = Epigeon(msg.sender);
}
function getPublicKeyForAddress (address owner) public view returns (string key){
return addressToPublicKey[owner];
}
function getUserNameForAddress (address owner) public view returns (string name){
return addressToUserName[owner];
}
function setPublicKeyToAddress (string key) public {
addressToPublicKey[msg.sender] = key;
}
function setUniqueNamePrice (uint256 price) public {
require(msg.sender == epigeonAddress.owner(), "Only Epigeon owner");
uniqueNamePrice = price;
}
function setUserNameToAddress (string name) public payable {
require(userNameToAddress[name] == msg.sender || userNameToAddress[name] == 0, "Name is already in use");
require(msg.value >= uniqueNamePrice, "Not enough value");
delete userNameToAddress[addressToUserName[msg.sender]];
addressToUserName[msg.sender] = name;
userNameToAddress[name] = msg.sender;
epigeonAddress.owner().transfer(address(this).balance);
}
function transferUniqueName (address toAddress) public {
addressToUserName[toAddress]= addressToUserName[msg.sender];
userNameToAddress[addressToUserName[toAddress]] = toAddress;
delete addressToUserName[msg.sender];
}
}
//----------------------------------------------------------------------------------------------------
contract PigeonDestinationDirectory is IPigeonDestinationDirectory{
address public epigeonAddress;
mapping (address => address[]) internal toAddressToPigeon;
mapping (address => uint256) internal pigeonToToAddressIndex;
mapping (address => bool) internal pigeonToAddressExists;
event PigeonSent(address toAddress);
constructor (){
epigeonAddress = msg.sender;
}
function changeToAddress(address newToAddress, address oldToAddress) public {
//Check if the call is from a CryptoPigeon
require(_isPigeon(msg.sender), "Available only for Epigeon's pigeon contracts");
ICryptoPigeon pigeon = ICryptoPigeon(msg.sender);
require(pigeonToAddressExists[msg.sender] == true, "Pigeon has no recipient entry to change");
//Push new to address
toAddressToPigeon[newToAddress].push(pigeon);
pigeonToToAddressIndex[pigeon] = toAddressToPigeon[newToAddress].length-1;
//Delete old to address
address pigeonToRemove = pigeon;
uint256 pigeonToRemoveIndex = pigeonToToAddressIndex[pigeon];
uint256 lastIdIndex = toAddressToPigeon[oldToAddress].length - 1;
if (toAddressToPigeon[oldToAddress][lastIdIndex] != pigeonToRemove)
{
address lastPigeon = toAddressToPigeon[oldToAddress][lastIdIndex];
toAddressToPigeon[oldToAddress][pigeonToToAddressIndex[pigeonToRemove]] = lastPigeon;
pigeonToToAddressIndex[lastPigeon] = pigeonToRemoveIndex;
}
delete toAddressToPigeon[oldToAddress][lastIdIndex];
toAddressToPigeon[oldToAddress].length--;
emit PigeonSent(newToAddress);
}
function deleteToAddress(address oldToAddress) public {
//Check if the call is from a CryptoPigeon
require(_isPigeon(msg.sender), "Available only for Epigeon's pigeon contracts");
ICryptoPigeon pigeon = ICryptoPigeon(msg.sender);
//Delete old to address
address pigeonToRemove = pigeon;
uint256 pigeonToRemoveIndex = pigeonToToAddressIndex[pigeon];
uint256 lastIdIndex = toAddressToPigeon[oldToAddress].length - 1;
if (toAddressToPigeon[oldToAddress][lastIdIndex] != pigeonToRemove)
{
address lastPigeon = toAddressToPigeon[oldToAddress][lastIdIndex];
toAddressToPigeon[oldToAddress][pigeonToToAddressIndex[pigeonToRemove]] = lastPigeon;
pigeonToToAddressIndex[lastPigeon] = pigeonToRemoveIndex;
}
delete toAddressToPigeon[oldToAddress][lastIdIndex];
toAddressToPigeon[oldToAddress].length--;
pigeonToAddressExists[pigeon] = false;
}
function deleteToAddressByEpigeon(address pigeon) public {
require(epigeonAddress == msg.sender, "Available only for Epigeon Smart Contract");
address pToAddress = ICryptoPigeon(pigeon).toAddress();
address pigeonToRemove = pigeon;
//Delete to address
if (ICryptoPigeon(pigeon).hasFlown()){
uint256 pigeonToRemoveIndex = pigeonToToAddressIndex[pigeon];
uint256 lastIdIndex = toAddressToPigeon[pToAddress].length - 1;
if (toAddressToPigeon[pToAddress][lastIdIndex] != pigeonToRemove)
{
address alastPigeon = toAddressToPigeon[pToAddress][lastIdIndex];
toAddressToPigeon[pToAddress][pigeonToToAddressIndex[pigeonToRemove]] = alastPigeon;
pigeonToToAddressIndex[alastPigeon] = pigeonToRemoveIndex;
}
delete toAddressToPigeon[pToAddress][lastIdIndex];
toAddressToPigeon[pToAddress].length--;
}
pigeonToAddressExists[pigeon] = false;
}
function pigeonSentToAddressByIndex(address toAddress, uint index) public view returns (address rpaddress){
rpaddress = toAddressToPigeon[toAddress][index];
}
function pigeonsSentToAddressLenght(address toAddress) public view returns (uint256 length){
length = toAddressToPigeon[toAddress].length;
}
function setToAddress(address newToAddress) public {
//Check if the call is from a CryptoPigeon
require(_isPigeon(msg.sender), "Available only for Epigeon's pigeon contracts");
ICryptoPigeon pigeon = ICryptoPigeon(msg.sender);
//Push new to address
require(pigeonToAddressExists[msg.sender] != true, "Pigeon already has recipient entry");
toAddressToPigeon[newToAddress].push(pigeon);
pigeonToToAddressIndex[pigeon] = toAddressToPigeon[newToAddress].length-1;
pigeonToAddressExists[pigeon] = true;
emit PigeonSent(newToAddress);
}
function _isPigeon (address sender) internal view returns (bool indeed){
ICryptoPigeon pigeon = ICryptoPigeon(sender);
return IEpigeon(epigeonAddress).validPigeon(sender, pigeon.owner());
}
}
//----------------------------------------------------------------------------------------------------
contract Epigeon is IEpigeon{
address public owner;
string public egigeonURI;
address private _nftContractAddress;
INameAndPublicKeyDirectory private _nameAndKeyDirectory;
IPigeonDestinationDirectory private _pigeonDestinations;
uint256[] factoryIds;
mapping (address => bool) disabledFactories;
mapping (uint256 => address) factoryIdtoAddress;
mapping (address => address[]) internal ownerToPigeon;
mapping (address => uint256) internal pigeonToOwnerIndex;
event PigeonCreated(ICryptoPigeon pigeon);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor (){
owner = msg.sender;
_nameAndKeyDirectory = new NameAndPublicKeyDirectory();
_pigeonDestinations = new PigeonDestinationDirectory();
}
function addFactory(address factoryAddress) public {
require(msg.sender == owner, "Only owner");
IPigeonFactory factory = IPigeonFactory(factoryAddress);
require(factory.iAmFactory(), "Not a factory");
require(factory.amIEpigeon(), "Not the factory's Epigeon");
require(factoryIdtoAddress[factory.factoryId()] == address(0), "Existing Factory ID");
factoryIds.push(factory.factoryId());
factoryIdtoAddress[factory.factoryId()] = factory;
disabledFactories[factory] = false;
}
function burnPigeon(address pigeon) public {
require((_nftContractAddress == msg.sender) || ((IEpigeonNFT(_nftContractAddress).isTokenizedPigeon(pigeon) == false) && (ICryptoPigeon(pigeon).owner() == msg.sender)), "Not authorized");
address pOwner = ICryptoPigeon(pigeon).owner();
address pigeonToRemove = pigeon;
//Delete old owner address
uint256 pigeonToRemoveIndex = pigeonToOwnerIndex[pigeon];
uint256 lastIdIndex = ownerToPigeon[pOwner].length - 1;
if (ownerToPigeon[pOwner][lastIdIndex] != pigeonToRemove)
{
address lastPigeon = ownerToPigeon[pOwner][lastIdIndex];
ownerToPigeon[pOwner][pigeonToOwnerIndex[pigeonToRemove]] = lastPigeon;
pigeonToOwnerIndex[lastPigeon] = pigeonToRemoveIndex;
}
delete ownerToPigeon[pOwner][lastIdIndex];
ownerToPigeon[pOwner].length--;
//Delete to address
_pigeonDestinations.deleteToAddressByEpigeon(pigeon);
//Burn contract too
ICryptoPigeon(pigeon).burnPigeon();
}
function createCryptoPigeon(uint256 factoryId) public payable returns (address pigeonAddress) {
require(msg.value >= getPigeonPriceForFactory(factoryId), "Not enough value");
return _createPigeon(msg.sender, factoryId);
}
function createCryptoPigeonByLatestFactory() public payable returns (address pigeonAddress) {
require(msg.value >= getPigeonPriceForFactory(getLastFactoryId()), "Not enough value");
return _createPigeon(msg.sender, getLastFactoryId());
}
function createCryptoPigeonForToken(address ERC20Token, uint256 factoryId) public returns (address pigeonAddress) {
require(getPigeonTokenPriceForFactory(ERC20Token, factoryId) > 0, "Price for token not available");
require(IERC20(ERC20Token).balanceOf(msg.sender) >= getPigeonTokenPriceForFactory(ERC20Token, factoryId), "Not enough balance");
require(IERC20(ERC20Token).allowance(msg.sender, address(this)) >= getPigeonTokenPriceForFactory(ERC20Token, factoryId), "Not enough allowance");
IERC20(ERC20Token).transferFrom(msg.sender, owner, getPigeonTokenPriceForFactory(ERC20Token, factoryId));
return _createPigeon(msg.sender, factoryId);
}
function createCryptoPigeonNFT(address to, uint256 factoryId) public returns (address pigeonAddress) {
require(_nftContractAddress == msg.sender, "Available only for the NFT contract");
return _createPigeon(to, factoryId);
}
function disableFactory(uint256 factoryId) public {
require(msg.sender == owner, "Only owner");
disabledFactories[factoryIdtoAddress[factoryId]] = true;
}
function enableFactory(uint256 factoryId) public {
require(msg.sender == owner, "Only owner");
require(factoryIdtoAddress[factoryId] != address(0));
disabledFactories[factoryIdtoAddress[factoryId]] = false;
}
function getFactoryAddresstoId(uint256 id) public view returns (address factory){
return factoryIdtoAddress[id];
}
function getFactoryCount() public view returns (uint256 count){
return factoryIds.length;
}
function getIdforFactory(uint256 index) public view returns (uint256 id){
return factoryIds[index];
}
function getLastFactoryId() public view returns (uint256 id){
return factoryIds[factoryIds.length-1];
}
function getPigeonPriceForFactory(uint256 factoryId) public view returns (uint256 price){
return IPigeonFactory(factoryIdtoAddress[factoryId]).mintingPrice();
}
function getPigeonTokenPriceForFactory(address ERC20Token, uint256 factoryId) public view returns (uint256 price){
return IPigeonFactory(factoryIdtoAddress[factoryId]).getFactoryTokenPrice(ERC20Token);
}
function isFactoryDisabled(address factoryAddress) public view returns (bool disabled){
return disabledFactories[factoryAddress];
}
function nameAndKeyDirectory() external view returns (INameAndPublicKeyDirectory directory){
return _nameAndKeyDirectory;
}
function nftContractAddress() external view returns (address _nftcontract){
return _nftContractAddress;
}
function payout() public {
require(msg.sender == owner, "Only owner");
owner.transfer(address(this).balance);
}
function pigeonDestinations() external view returns (IPigeonDestinationDirectory destinations){
return _pigeonDestinations;
}
function pigeonsCountOfOwner(address pigeonOwner) public view returns (uint256 length){
length = ownerToPigeon[pigeonOwner].length;
return length;
}
function pigeonOfOwnerByIndex(address pigeonOwner, uint index) public view returns (address rpaddress){
rpaddress = ownerToPigeon[pigeonOwner][index];
return rpaddress;
}
function setNFTContractAddress(address nftContract) public {
require(owner == msg.sender, "Only owner");
require(_nftContractAddress == address(0), "NFT contract already set");
_nftContractAddress = nftContract;
}
function setUri(string uri) public {
require(owner == msg.sender, "Only owner");
egigeonURI = uri;
}
function transferOwnership(address newOwner) public {
require(owner == msg.sender, "Only owner");
require(newOwner != address(0), "Zero address");
emit OwnershipTransferred(owner, newOwner);
owner.transfer(address(this).balance);
owner = newOwner;
}
function transferPigeon(address from, address to, address pigeon) public {
if (IEpigeonNFT(_nftContractAddress).isTokenizedPigeon(pigeon)) {
require(_nftContractAddress == msg.sender, "Tokenized Pigeon can only be transferred by NFT contract");
}
else{
require(ICryptoPigeon(pigeon).owner() == msg.sender || pigeon == msg.sender, "Only pigeon owner");
}
//Push new owner address
ownerToPigeon[to].push(pigeon);
pigeonToOwnerIndex[pigeon] = ownerToPigeon[to].length-1;
//Delete old owner address
address pigeonToRemove = pigeon;
uint256 pigeonToRemoveIndex = pigeonToOwnerIndex[pigeon];
uint256 lastIdIndex = ownerToPigeon[from].length - 1;
if (ownerToPigeon[from][lastIdIndex] != pigeonToRemove)
{
address lastPigeon = ownerToPigeon[from][lastIdIndex];
ownerToPigeon[from][pigeonToOwnerIndex[pigeonToRemove]] = lastPigeon;
pigeonToOwnerIndex[lastPigeon] = pigeonToRemoveIndex;
}
delete ownerToPigeon[from][lastIdIndex];
ownerToPigeon[from].length--;
//Delete old to address
_pigeonDestinations.deleteToAddressByEpigeon(pigeon);
//Transfer contract too
ICryptoPigeon(pigeon).transferPigeon(to);
}
function validPigeon(address pigeon, address pigeonOwner) public view returns (bool valid){
require(pigeon != address(0), "Null address");
return ownerToPigeon[pigeonOwner][pigeonToOwnerIndex[pigeon]] == pigeon;
}
function _createPigeon(address to, uint256 factoryId) internal returns (address pigeonAddress) {
require(isFactoryDisabled(factoryIdtoAddress[factoryId]) == false, "Factory is disabled");
ICryptoPigeon pigeon = IPigeonFactory(factoryIdtoAddress[factoryId]).createCryptoPigeon( to);
ownerToPigeon[to].push(pigeon);
pigeonToOwnerIndex[pigeon] = ownerToPigeon[to].length-1;
emit PigeonCreated(pigeon);
return pigeon;
}
}
|
----------------------------------------------------------------------------------------------------
|
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);
}
| 231,187
|
pragma solidity ^0.5.16;
import "./KUSDMinter.sol";
/**
* @title KUSDMinter is responsible to stake/unstake users' Kine MCD (see KMCD) and mint/burn KUSD (see KineUSD) on behalf of users.
* When user want to mint KUSD against their collaterals (see KToken), KUSDMinter will borrow Knie MCD on behalf of user (which will increase user's debt ratio)
* and then call KineUSD to mint KUSD to user. When user want to burn KUSD, KUSDMinter will call KineUSD to burn KUSD from user and repay Kine MCD on behalf of user.
* KUSDMinter also let treasury account to mint/burn its balance to keep KUSD amount (the part that user transferred into Kine off-chain trading system) synced with Kine off-chain trading system.
* @author Kine
*
* V2 changes:
* 1. available to change reward token after each period end, rewards not claimed yet will convert to new reward token according to given scale param
* 2. add scaleParamIndex in AccountRewardDetail
* 3. add currentScaleParamIndex to note current reward token index
* 4. add scaleParams to record history scale params in order to calculate user's reward correctly
*
* V3 changes:
* 1. add liquidator whitelist
*/
interface LiquidatorWhitelistInterface {
function isListed(address liquidatorToVerify) external view returns (bool);
}
contract KUSDMinterV3 is IRewardDistributionRecipient {
using KineSafeMath for uint;
using SafeERC20 for IERC20;
/// @notice Emitted when KMCD changed
event NewKMCD(address oldKMCD, address newKMCD);
/// @notice Emitted when KineUSD changed
event NewKUSD(address oldKUSD, address newKUSD);
/// @notice Emitted when reward token changed
event NewRewardToken(address oldRewardToken, address newRewardToken, uint scaleParam, uint leftOverReward, uint replaceReward, address leftoverTokenReceipient);
/// @notice Emitted when reward duration changed
event NewRewardDuration(uint oldRewardDuration, uint newRewardDuration);
/// @notice Emitted when reward release period changed
event NewRewardReleasePeriod(uint oldRewardReleasePeriod, uint newRewardReleasePeriod);
/// @notice Emitted when burn cool down time changed
event NewBurnCooldownTime(uint oldCooldown, uint newCooldownTime);
/// @notice Emitted when user mint KUSD
event Mint(address indexed user, uint mintKUSDAmount, uint stakedKMCDAmount, uint userStakesNew, uint totalStakesNew);
/// @notice Emitted when user burnt KUSD
event Burn(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew);
/// @notice Emitted when user burnt maximum KUSD
event BurnMax(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew);
/// @notice Emitted when liquidator liquidate staker's Kine MCD
event Liquidate(address indexed liquidator, address indexed staker, uint burntKUSDAmount, uint unstakedKMCDAmount, uint stakerStakesNew, uint totalStakesNew);
/// @notice Emitted when distributor notify reward is added
event RewardAdded(uint reward);
/// @notice Emitted when user claimed reward
event RewardPaid(address indexed user, uint reward);
/// @notice Emitted when treasury account mint kusd
event TreasuryMint(uint amount);
/// @notice Emitted when treasury account burn kusd
event TreasuryBurn(uint amount);
/// @notice Emitted when treasury account changed
event NewTreasury(address oldTreasury, address newTreasury);
/// @notice Emitted when vault account changed
event NewVault(address oldVault, address newVault);
/// @notice Emitted when controller changed
event NewController(address oldController, address newController);
/// @notice Emitted when liquidator whitelist changed
event NewLiquidatorWhitelist(address oldLiquidatorWhitelist, address newLiquidatorWhitelist);
/**
* @notice This is for avoiding reward calculation overflow (see https://sips.synthetix.io/sips/sip-77)
* 1.15792e59 < uint(-1) / 1e18
*/
uint public constant REWARD_OVERFLOW_CHECK = 1.15792e59;
/**
* @notice Implementation address slot for delegation mode;
*/
address public implementation;
/// @notice Flag to mark if this contract has been initialized before
bool public initialized;
/// @notice Contract which holds Kine MCD
IKMCD public kMCD;
/// @notice Contract which holds Kine USD
IKineUSD public kUSD;
/// @notice Contract of controller which holds Kine Oracle
KineControllerInterface public controller;
/// @notice Treasury is responsible to keep KUSD amount consisted with Kine off-chain trading system
address public treasury;
/// @notice Vault is the place to store Kine trading system's reserved KUSD
address public vault;
/****************
* Reward related
****************/
/// @notice Contract which hold Kine Token
IERC20 public rewardToken;
/// @notice Reward distribution duration. Added reward will be distribute to Kine MCD stakers within this duration.
uint public rewardDuration;
/// @notice Staker's reward will mature gradually in this period.
uint public rewardReleasePeriod;
/// @notice Start time that users can start staking/burning KUSD and claim their rewards.
uint public startTime;
/// @notice End time of this round of reward distribution.
uint public periodFinish = 0;
/// @notice Per second reward to be distributed
uint public rewardRate = 0;
/// @notice Accrued reward per Kine MCD staked per second.
uint public rewardPerTokenStored;
/// @notice Last time that rewardPerTokenStored is updated. Happens whenever total stakes going to be changed.
uint public lastUpdateTime;
/**
* @notice The minium cool down time before user can burn kUSD after they mint kUSD everytime.
* This is to raise risk and cost to arbitrageurs who front run our prices updates in oracle to drain profit from stakers.
* Should be larger then minium price post interval.
*/
uint public burnCooldownTime;
struct AccountRewardDetail {
/// @dev Last time account claimed its reward
uint lastClaimTime;
/// @dev RewardPerTokenStored at last time accrue rewards to this account
uint rewardPerTokenUpdated;
/// @dev Accrued rewards haven't been claimed of this account
uint accruedReward;
/// @dev Last time account mint kUSD
uint lastMintTime;
/// @dev Sys scale param when last time account reward detail updated
uint scaleParamIndex;
}
/// @notice Mapping of account addresses to account reward detail
mapping(address => AccountRewardDetail) public accountRewardDetails;
/// to support change reward token when duration end
/// @notice system wide index of scale param
uint public currentScaleParamIndex;
/// @notice everytime owner change reward token, will save scale param of old reward token to new reward token
uint[] public scaleParams;
/// @notice liquidator checker
LiquidatorWhitelistInterface public liquidatorWhitelist;
function initialize(address rewardToken_, address kUSD_, address kMCD_, address controller_, address treasury_, address vault_, address rewardDistribution_, uint startTime_, uint rewardDuration_, uint rewardReleasePeriod_) external {
require(initialized == false, "KUSDMinter can only be initialized once");
rewardToken = IERC20(rewardToken_);
kUSD = IKineUSD(kUSD_);
kMCD = IKMCD(kMCD_);
controller = KineControllerInterface(controller_);
treasury = treasury_;
vault = vault_;
rewardDistribution = rewardDistribution_;
startTime = startTime_;
rewardDuration = rewardDuration_;
rewardReleasePeriod = rewardReleasePeriod_;
initialized = true;
}
/**
* @dev Local vars in calculating equivalent amount between KUSD and Kine MCD
*/
struct CalculateVars {
uint equivalentKMCDAmount;
uint equivalentKUSDAmount;
}
/// @notice Prevent stakers' actions before start time
modifier checkStart() {
require(block.timestamp >= startTime, "not started yet");
_;
}
/// @notice Prevent accounts other than treasury to mint/burn KUSD
modifier onlyTreasury() {
require(msg.sender == treasury, "only treasury account is allowed");
_;
}
modifier afterCooldown(address staker) {
require(accountRewardDetails[staker].lastMintTime.add(burnCooldownTime) < block.timestamp, "burn still cooling down");
_;
}
/***
* @notice Accrue account's rewards and store this time accrued results
* @param account Reward status of whom to be updated
*/
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
accountRewardDetails[account].accruedReward = earned(account);
accountRewardDetails[account].rewardPerTokenUpdated = rewardPerTokenStored;
accountRewardDetails[account].scaleParamIndex = currentScaleParamIndex;
if (accountRewardDetails[account].lastClaimTime == 0) {
accountRewardDetails[account].lastClaimTime = block.timestamp;
}
}
_;
}
/// @dev reverts if the caller is not a certified liquidator
modifier checkLiquidator() {
LiquidatorWhitelistInterface lc = liquidatorWhitelist;
require(address(lc) != address(0) && lc.isListed(msg.sender), "not valid liquidator");
_;
}
/**
* @notice Current time which hasn't past this round reward's duration.
* @return Current timestamp that hasn't past this round rewards' duration.
*/
function lastTimeRewardApplicable() public view returns (uint) {
return Math.min(block.timestamp, periodFinish);
}
/**
* @notice Calculate new accrued reward per staked Kine MCD.
* @return Current accrued reward per staked Kine MCD.
*/
function rewardPerToken() public view returns (uint) {
uint totalStakes = totalStakes();
if (totalStakes == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalStakes)
);
}
/**
* @notice Calculate account's earned rewards so far.
* @param account Which account to be viewed.
* @return Account's earned rewards so far.
*/
function earned(address account) public view returns (uint) {
AccountRewardDetail memory detail = accountRewardDetails[account];
uint scaledRewardPerTokenUpdated = detail.rewardPerTokenUpdated;
uint scaledAccruedReward = detail.accruedReward;
for (uint i = detail.scaleParamIndex; i < currentScaleParamIndex; i++) {
scaledRewardPerTokenUpdated = scaledRewardPerTokenUpdated.mul(scaleParams[i]).div(1e18);
scaledAccruedReward = scaledAccruedReward.mul(scaleParams[i]).div(1e18);
}
return accountStakes(account)
.mul(rewardPerToken().sub(scaledRewardPerTokenUpdated))
.div(1e18)
.add(scaledAccruedReward);
}
/**
* @notice Calculate account's claimable rewards so far.
* @param account Which account to be viewed.
* @return Account's claimable rewards so far.
*/
function claimable(address account) external view returns (uint) {
uint accountNewAccruedReward = earned(account);
uint pastTime = block.timestamp.sub(accountRewardDetails[account].lastClaimTime);
uint maturedReward = rewardReleasePeriod == 0 ? accountNewAccruedReward : accountNewAccruedReward.mul(pastTime).div(rewardReleasePeriod);
if (maturedReward > accountNewAccruedReward) {
maturedReward = accountNewAccruedReward;
}
return maturedReward;
}
/**
* @notice Mint will borrow equivalent Kine MCD for user, stake borrowed MCD and mint specified amount of KUSD. Call will fail if hasn't reached start time.
* Mint will fail if hasn't reach start time.
* @param kUSDAmount The amount of KUSD user want to mint
*/
function mint(uint kUSDAmount) external checkStart updateReward(msg.sender) {
address payable msgSender = _msgSender();
// update sender's mint time
accountRewardDetails[msgSender].lastMintTime = block.timestamp;
uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD));
require(kMCDPriceMantissa != 0, "Mint: get Kine MCD price zero");
CalculateVars memory vars;
// KUSD has 18 decimals
// KMCD has 18 decimals
// kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18
// so the calculation of equivalent Kine MCD amount is as below
// kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18
// equivalentKMCDAmount = ----------- * ------------------ * 1e18 = -----------------
// 1e18 kMCDPriceMantissa kMCDPriceMantissa
vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa);
// call KMCD contract to borrow Kine MCD for user and stake them
kMCD.borrowBehalf(msgSender, vars.equivalentKMCDAmount);
// mint KUSD to user
kUSD.mint(msgSender, kUSDAmount);
emit Mint(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes());
}
/**
* @notice Burn repay equivalent Kine MCD for user and burn specified amount of KUSD
* Burn will fail if hasn't reach start time.
* @param kUSDAmount The amount of KUSD user want to burn
*/
function burn(uint kUSDAmount) external checkStart afterCooldown(msg.sender) updateReward(msg.sender) {
address msgSender = _msgSender();
// burn user's KUSD
kUSD.burn(msgSender, kUSDAmount);
// calculate equivalent Kine MCD amount to specified amount of KUSD
uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD));
require(kMCDPriceMantissa != 0, "Burn: get Kine MCD price zero");
CalculateVars memory vars;
// KUSD has 18 decimals
// KMCD has 18 decimals
// kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18
// so the calculation of equivalent Kine MCD amount is as below
// kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18
// equivalentKMCDAmount = ----------- * ------------------ * 1e18 = -----------------
// 1e18 kMCDPriceMantissa kMCDPriceMantissa
vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa);
// call KMCD contract to repay Kine MCD for user
kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount);
emit Burn(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes());
}
/**
* @notice BurnMax unstake and repay all borrowed Kine MCD for user and burn equivalent KUSD
*/
function burnMax() external checkStart afterCooldown(msg.sender) updateReward(msg.sender) {
address msgSender = _msgSender();
uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD));
require(kMCDPriceMantissa != 0, "BurnMax: get Kine MCD price zero");
CalculateVars memory vars;
// KUSD has 18 decimals
// KMCD has 18 decimals
// kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18
// so the calculation of equivalent KUSD amount is as below
// accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa
// equivalentKUSDAmount = ------------- * ------------------ * 1e18 = ---------------------------------
// 1e18 1e12 * 1e6 1e18
//
// try to unstake all Kine MCD
uint userStakes = accountStakes(msgSender);
vars.equivalentKMCDAmount = userStakes;
vars.equivalentKUSDAmount = userStakes.mul(kMCDPriceMantissa).div(1e18);
// in case user's kUSD is not enough to unstake all mcd, then just burn all kUSD and unstake part of MCD
uint kUSDbalance = kUSD.balanceOf(msgSender);
if (vars.equivalentKUSDAmount > kUSDbalance) {
vars.equivalentKUSDAmount = kUSDbalance;
vars.equivalentKMCDAmount = kUSDbalance.mul(1e18).div(kMCDPriceMantissa);
}
// burn user's equivalent KUSD
kUSD.burn(msgSender, vars.equivalentKUSDAmount);
// call KMCD contract to repay Kine MCD for user
kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount);
emit BurnMax(msgSender, vars.equivalentKUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes());
}
/**
* @notice Caller liquidates the staker's Kine MCD and seize staker's collateral.
* Liquidate will fail if hasn't reach start time.
* @param staker The staker of Kine MCD to be liquidated.
* @param unstakeKMCDAmount The amount of Kine MCD to unstake.
* @param maxBurnKUSDAmount The max amount limit of KUSD of liquidator to be burned.
* @param kTokenCollateral The market in which to seize collateral from the staker.
*/
function liquidate(address staker, uint unstakeKMCDAmount, uint maxBurnKUSDAmount, address kTokenCollateral, uint minSeizeKToken) external checkLiquidator checkStart updateReward(staker) {
address msgSender = _msgSender();
uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD));
require(kMCDPriceMantissa != 0, "Liquidate: get Kine MCD price zero");
CalculateVars memory vars;
// KUSD has 18 decimals
// KMCD has 18 decimals
// kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18
// so the calculation of equivalent KUSD amount is as below
// accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa
// equivalentKUSDAmount = ------------- * ------------------ * 1e18 = ---------------------------------
// 1e18 1e12 * 1e6 1e30
//
vars.equivalentKUSDAmount = unstakeKMCDAmount.mul(kMCDPriceMantissa).div(1e18);
require(maxBurnKUSDAmount >= vars.equivalentKUSDAmount, "Liquidate: reach out max burn KUSD amount limit");
// burn liquidator's KUSD
kUSD.burn(msgSender, vars.equivalentKUSDAmount);
// call KMCD contract to liquidate staker's Kine MCD and seize collateral
kMCD.liquidateBorrowBehalf(msgSender, staker, unstakeKMCDAmount, kTokenCollateral, minSeizeKToken);
emit Liquidate(msgSender, staker, vars.equivalentKUSDAmount, unstakeKMCDAmount, accountStakes(staker), totalStakes());
}
/**
* @notice Show account's staked Kine MCD amount
* @param account The account to be get MCD amount from
*/
function accountStakes(address account) public view returns (uint) {
return kMCD.borrowBalance(account);
}
/// @notice Show total staked Kine MCD amount
function totalStakes() public view returns (uint) {
return kMCD.totalBorrows();
}
/**
* @notice Claim the matured rewards of caller.
* Claim will fail if hasn't reach start time.
*/
function getReward() external checkStart updateReward(msg.sender) {
uint reward = accountRewardDetails[msg.sender].accruedReward;
if (reward > 0) {
uint pastTime = block.timestamp.sub(accountRewardDetails[msg.sender].lastClaimTime);
uint maturedReward = rewardReleasePeriod == 0 ? reward : reward.mul(pastTime).div(rewardReleasePeriod);
if (maturedReward > reward) {
maturedReward = reward;
}
accountRewardDetails[msg.sender].accruedReward = reward.sub(maturedReward);
accountRewardDetails[msg.sender].lastClaimTime = block.timestamp;
rewardToken.safeTransfer(msg.sender, maturedReward);
emit RewardPaid(msg.sender, maturedReward);
}
}
/**
* @notice Notify rewards has been added, trigger a new round of reward period, recalculate reward rate and duration end time.
* If distributor notify rewards before this round duration end time, then the leftover rewards of this round will roll over to
* next round and will be distributed together with new rewards in next round of reward period.
* @param reward How many of rewards has been added for new round of reward period.
*/
function notifyRewardAmount(uint reward) external onlyRewardDistribution updateReward(address(0)) {
if (block.timestamp > startTime) {
if (block.timestamp >= periodFinish) {
// @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range
// which is 2^256 / 10^18
require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow");
rewardRate = reward.div(rewardDuration);
} else {
uint remaining = periodFinish.sub(block.timestamp);
uint leftover = remaining.mul(rewardRate);
// @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range
// which is 2^256 / 10^18
require(reward.add(leftover) < REWARD_OVERFLOW_CHECK, "reward rate will overflow");
rewardRate = reward.add(leftover).div(rewardDuration);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardDuration);
emit RewardAdded(reward);
} else {
// @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range
// which is 2^256 / 10^18
require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow");
rewardRate = reward.div(rewardDuration);
lastUpdateTime = startTime;
periodFinish = startTime.add(rewardDuration);
emit RewardAdded(reward);
}
}
/**
* @notice Set new reward duration, will start a new round of reward period immediately and recalculate rewardRate.
* @param newRewardDuration New duration of each reward period round.
*/
function _setRewardDuration(uint newRewardDuration) external onlyOwner updateReward(address(0)) {
uint oldRewardDuration = rewardDuration;
rewardDuration = newRewardDuration;
if (block.timestamp > startTime) {
if (block.timestamp >= periodFinish) {
rewardRate = 0;
} else {
uint remaining = periodFinish.sub(block.timestamp);
uint leftover = remaining.mul(rewardRate);
rewardRate = leftover.div(rewardDuration);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardDuration);
} else {
rewardRate = rewardRate.mul(oldRewardDuration).div(rewardDuration);
lastUpdateTime = startTime;
periodFinish = startTime.add(rewardDuration);
}
emit NewRewardDuration(oldRewardDuration, newRewardDuration);
}
/**
* @notice Set new reward release period. The unclaimed rewards will be affected immediately.
* @param newRewardReleasePeriod New release period of how long all earned rewards will be matured each time
* before user claim reward.
*/
function _setRewardReleasePeriod(uint newRewardReleasePeriod) external onlyOwner updateReward(address(0)) {
uint oldRewardReleasePeriod = rewardReleasePeriod;
rewardReleasePeriod = newRewardReleasePeriod;
emit NewRewardReleasePeriod(oldRewardReleasePeriod, newRewardReleasePeriod);
}
function _setCooldownTime(uint newCooldownTime) external onlyOwner {
uint oldCooldown = burnCooldownTime;
burnCooldownTime = newCooldownTime;
emit NewBurnCooldownTime(oldCooldown, newCooldownTime);
}
/**
* @notice Mint KUSD to treasury account to keep on-chain KUSD consist with off-chain trading system
* @param amount The amount of KUSD to mint to treasury
*/
function treasuryMint(uint amount) external onlyTreasury {
kUSD.mint(vault, amount);
emit TreasuryMint(amount);
}
/**
* @notice Burn KUSD from treasury account to keep on-chain KUSD consist with off-chain trading system
* @param amount The amount of KUSD to burn from treasury
*/
function treasuryBurn(uint amount) external onlyTreasury {
kUSD.burn(vault, amount);
emit TreasuryBurn(amount);
}
/**
* @notice Change treasury account to a new one
* @param newTreasury New treasury account address
*/
function _setTreasury(address newTreasury) external onlyOwner {
address oldTreasury = treasury;
treasury = newTreasury;
emit NewTreasury(oldTreasury, newTreasury);
}
/**
* @notice Change vault account to a new one
* @param newVault New vault account address
*/
function _setVault(address newVault) external onlyOwner {
address oldVault = vault;
vault = newVault;
emit NewVault(oldVault, newVault);
}
/**
* @notice Change KMCD contract address to a new one.
* @param newKMCD New KMCD contract address.
*/
function _setKMCD(address newKMCD) external onlyOwner {
address oldKMCD = address(kMCD);
kMCD = IKMCD(newKMCD);
emit NewKMCD(oldKMCD, newKMCD);
}
/**
* @notice Change KUSD contract address to a new one.
* @param newKUSD New KineUSD contract address.
*/
function _setKUSD(address newKUSD) external onlyOwner {
address oldKUSD = address(kUSD);
kUSD = IKineUSD(newKUSD);
emit NewKUSD(oldKUSD, newKUSD);
}
/**
* @notice Change Kine Controller address to a new one.
* @param newController New Controller contract address.
*/
function _setController(address newController) external onlyOwner {
address oldController = address(controller);
controller = KineControllerInterface(newController);
emit NewController(oldController, newController);
}
function _changeRewardToken(address newRewardToken, uint scaleParam, address tokenHolder) external onlyOwner updateReward(address(0)) {
require(block.timestamp > periodFinish, "period not finished yet");
// 1. convert current rewardPerTokenStored to fit new token
rewardPerTokenStored = rewardPerTokenStored.mul(scaleParam).div(1e18);
rewardRate = rewardRate.mul(scaleParam).div(1e18);
// 2. save scaleParam to array and update sys scaleParamIndex
scaleParams.push(scaleParam);
currentScaleParamIndex++;
// 3. transfer left-over old reward token to tokenHolder
uint leftOverReward = rewardToken.balanceOf(address(this));
rewardToken.safeTransfer(tokenHolder, leftOverReward);
// 4. set newRewardToken
address oldRewardToken = address(rewardToken);
rewardToken = IERC20(newRewardToken);
// 5. transfer equivalent new reward token to this contract
uint replaceReward = leftOverReward.mul(scaleParam).div(1e18);
rewardToken.safeTransferFrom(tokenHolder, address(this), replaceReward);
emit NewRewardToken(oldRewardToken, newRewardToken, scaleParam, leftOverReward, replaceReward, tokenHolder);
}
/**
* @notice Change liquidator whitelist address to a new one.
* @param newLiquidatorWhitelist New whitelist contract address.
*/
function _setLiquidatorWhitelist(address newLiquidatorWhitelist) external onlyOwner {
address oldLiquidatorWhitelist = address(liquidatorWhitelist);
require(oldLiquidatorWhitelist != newLiquidatorWhitelist, "same address");
liquidatorWhitelist = LiquidatorWhitelistInterface(newLiquidatorWhitelist);
emit NewLiquidatorWhitelist(oldLiquidatorWhitelist, newLiquidatorWhitelist);
}
}
pragma solidity ^0.5.16;
import "./KineOracleInterface.sol";
import "./KineControllerInterface.sol";
import "./KUSDMinterDelegate.sol";
import "./Math.sol";
import "./IERC20.sol";
import "./ERC20.sol";
import "./SafeERC20.sol";
/// @notice IKineUSD, a simplified interface of KineUSD (see KineUSD)
interface IKineUSD {
function mint(address account, uint amount) external;
function burn(address account, uint amount) external;
function balanceOf(address account) external view returns (uint256);
}
/// @notice IKMCD, a simplified interface of KMCD (see KMCD)
interface IKMCD {
function borrowBehalf(address payable borrower, uint borrowAmount) external;
function repayBorrowBehalf(address borrower, uint repayAmount) external;
function liquidateBorrowBehalf(address liquidator, address borrower, uint repayAmount, address kTokenCollateral, uint minSeizeKToken) external;
function borrowBalance(address account) external view returns (uint);
function totalBorrows() external view returns (uint);
}
/**
* @title IRewardDistributionRecipient
*/
contract IRewardDistributionRecipient is KUSDMinterDelegate {
/// @notice Emitted when reward distributor changed
event NewRewardDistribution(address oldRewardDistribution, address newRewardDistribution);
/// @notice The reward distributor who is responsible to transfer rewards to this recipient and notify the recipient that reward is added.
address public rewardDistribution;
/// @notice Notify this recipient that reward is added.
function notifyRewardAmount(uint reward) external;
/// @notice Only reward distributor can notify that reward is added.
modifier onlyRewardDistribution() {
require(_msgSender() == rewardDistribution, "Caller is not reward distribution");
_;
}
/// @notice Set reward distributor to new one.
function setRewardDistribution(address _rewardDistribution) external onlyOwner {
address oldRewardDistribution = rewardDistribution;
rewardDistribution = _rewardDistribution;
emit NewRewardDistribution(oldRewardDistribution, _rewardDistribution);
}
}
/**
* @title KUSDMinter is responsible to stake/unstake users' Kine MCD (see KMCD) and mint/burn KUSD (see KineUSD) on behalf of users.
* When user want to mint KUSD against their collaterals (see KToken), KUSDMinter will borrow Knie MCD on behalf of user (which will increase user's debt ratio)
* and then call KineUSD to mint KUSD to user. When user want to burn KUSD, KUSDMinter will call KineUSD to burn KUSD from user and repay Kine MCD on behalf of user.
* KUSDMinter also let treasury account to mint/burn its balance to keep KUSD amount (the part that user transferred into Kine off-chain trading system) synced with Kine off-chain trading system.
* @author Kine
*/
contract KUSDMinter is IRewardDistributionRecipient {
using KineSafeMath for uint;
using SafeERC20 for IERC20;
/// @notice Emitted when KMCD changed
event NewKMCD(address oldKMCD, address newKMCD);
/// @notice Emitted when KineUSD changed
event NewKUSD(address oldKUSD, address newKUSD);
/// @notice Emitted when Kine changed
event NewKine(address oldKine, address newKine);
/// @notice Emitted when reward duration changed
event NewRewardDuration(uint oldRewardDuration, uint newRewardDuration);
/// @notice Emitted when reward release period changed
event NewRewardReleasePeriod(uint oldRewardReleasePeriod, uint newRewardReleasePeriod);
/// @notice Emitted when burn cool down time changed
event NewBurnCooldownTime(uint oldCooldown, uint newCooldownTime);
/// @notice Emitted when user mint KUSD
event Mint(address indexed user, uint mintKUSDAmount, uint stakedKMCDAmount, uint userStakesNew, uint totalStakesNew);
/// @notice Emitted when user burnt KUSD
event Burn(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew);
/// @notice Emitted when user burnt maximum KUSD
event BurnMax(address indexed user, uint burntKUSDAmount, uint unstakedKMCDAmount, uint userStakesNew, uint totalStakesNew);
/// @notice Emitted when liquidator liquidate staker's Kine MCD
event Liquidate(address indexed liquidator, address indexed staker, uint burntKUSDAmount, uint unstakedKMCDAmount, uint stakerStakesNew, uint totalStakesNew);
/// @notice Emitted when distributor notify reward is added
event RewardAdded(uint reward);
/// @notice Emitted when user claimed reward
event RewardPaid(address indexed user, uint reward);
/// @notice Emitted when treasury account mint kusd
event TreasuryMint(uint amount);
/// @notice Emitted when treasury account burn kusd
event TreasuryBurn(uint amount);
/// @notice Emitted when treasury account changed
event NewTreasury(address oldTreasury, address newTreasury);
/// @notice Emitted when vault account changed
event NewVault(address oldVault, address newVault);
/// @notice Emitted when controller changed
event NewController(address oldController, address newController);
/**
* @notice This is for avoiding reward calculation overflow (see https://sips.synthetix.io/sips/sip-77)
* 1.15792e59 < uint(-1) / 1e18
*/
uint public constant REWARD_OVERFLOW_CHECK = 1.15792e59;
/**
* @notice Implementation address slot for delegation mode;
*/
address public implementation;
/// @notice Flag to mark if this contract has been initialized before
bool public initialized;
/// @notice Contract which holds Kine MCD
IKMCD public kMCD;
/// @notice Contract which holds Kine USD
IKineUSD public kUSD;
/// @notice Contract of controller which holds Kine Oracle
KineControllerInterface public controller;
/// @notice Treasury is responsible to keep KUSD amount consisted with Kine off-chain trading system
address public treasury;
/// @notice Vault is the place to store Kine trading system's reserved KUSD
address public vault;
/****************
* Reward related
****************/
/// @notice Contract which hold Kine Token
IERC20 public kine;
/// @notice Reward distribution duration. Added reward will be distribute to Kine MCD stakers within this duration.
uint public rewardDuration;
/// @notice Staker's reward will mature gradually in this period.
uint public rewardReleasePeriod;
/// @notice Start time that users can start staking/burning KUSD and claim their rewards.
uint public startTime;
/// @notice End time of this round of reward distribution.
uint public periodFinish = 0;
/// @notice Per second reward to be distributed
uint public rewardRate = 0;
/// @notice Accrued reward per Kine MCD staked per second.
uint public rewardPerTokenStored;
/// @notice Last time that rewardPerTokenStored is updated. Happens whenever total stakes going to be changed.
uint public lastUpdateTime;
/**
* @notice The minium cool down time before user can burn kUSD after they mint kUSD everytime.
* This is to raise risk and cost to arbitrageurs who front run our prices updates in oracle to drain profit from stakers.
* Should be larger then minium price post interval.
*/
uint public burnCooldownTime;
struct AccountRewardDetail {
/// @dev Last time account claimed its reward
uint lastClaimTime;
/// @dev RewardPerTokenStored at last time accrue rewards to this account
uint rewardPerTokenUpdated;
/// @dev Accrued rewards haven't been claimed of this account
uint accruedReward;
/// @dev Last time account mint kUSD
uint lastMintTime;
}
/// @notice Mapping of account addresses to account reward detail
mapping(address => AccountRewardDetail) public accountRewardDetails;
function initialize(address kine_, address kUSD_, address kMCD_, address controller_, address treasury_, address vault_, address rewardDistribution_, uint startTime_, uint rewardDuration_, uint rewardReleasePeriod_) external {
require(initialized == false, "KUSDMinter can only be initialized once");
kine = IERC20(kine_);
kUSD = IKineUSD(kUSD_);
kMCD = IKMCD(kMCD_);
controller = KineControllerInterface(controller_);
treasury = treasury_;
vault = vault_;
rewardDistribution = rewardDistribution_;
startTime = startTime_;
rewardDuration = rewardDuration_;
rewardReleasePeriod = rewardReleasePeriod_;
initialized = true;
}
/**
* @dev Local vars in calculating equivalent amount between KUSD and Kine MCD
*/
struct CalculateVars {
uint equivalentKMCDAmount;
uint equivalentKUSDAmount;
}
/// @notice Prevent stakers' actions before start time
modifier checkStart() {
require(block.timestamp >= startTime, "not started yet");
_;
}
/// @notice Prevent accounts other than treasury to mint/burn KUSD
modifier onlyTreasury() {
require(msg.sender == treasury, "only treasury account is allowed");
_;
}
modifier afterCooldown(address staker) {
require(accountRewardDetails[staker].lastMintTime.add(burnCooldownTime) < block.timestamp, "burn still cooling down");
_;
}
/***
* @notice Accrue account's rewards and store this time accrued results
* @param account Reward status of whom to be updated
*/
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
accountRewardDetails[account].accruedReward = earned(account);
accountRewardDetails[account].rewardPerTokenUpdated = rewardPerTokenStored;
if (accountRewardDetails[account].lastClaimTime == 0) {
accountRewardDetails[account].lastClaimTime = block.timestamp;
}
}
_;
}
/**
* @notice Current time which hasn't past this round reward's duration.
* @return Current timestamp that hasn't past this round rewards' duration.
*/
function lastTimeRewardApplicable() public view returns (uint) {
return Math.min(block.timestamp, periodFinish);
}
/**
* @notice Calculate new accrued reward per staked Kine MCD.
* @return Current accrued reward per staked Kine MCD.
*/
function rewardPerToken() public view returns (uint) {
uint totalStakes = totalStakes();
if (totalStakes == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalStakes)
);
}
/**
* @notice Calculate account's earned rewards so far.
* @param account Which account to be viewed.
* @return Account's earned rewards so far.
*/
function earned(address account) public view returns (uint) {
return accountStakes(account)
.mul(rewardPerToken().sub(accountRewardDetails[account].rewardPerTokenUpdated))
.div(1e18)
.add(accountRewardDetails[account].accruedReward);
}
/**
* @notice Calculate account's claimable rewards so far.
* @param account Which account to be viewed.
* @return Account's claimable rewards so far.
*/
function claimable(address account) external view returns (uint) {
uint accountNewAccruedReward = earned(account);
uint pastTime = block.timestamp.sub(accountRewardDetails[account].lastClaimTime);
uint maturedReward = rewardReleasePeriod == 0 ? accountNewAccruedReward : accountNewAccruedReward.mul(pastTime).div(rewardReleasePeriod);
if (maturedReward > accountNewAccruedReward) {
maturedReward = accountNewAccruedReward;
}
return maturedReward;
}
/**
* @notice Mint will borrow equivalent Kine MCD for user, stake borrowed MCD and mint specified amount of KUSD. Call will fail if hasn't reached start time.
* Mint will fail if hasn't reach start time.
* @param kUSDAmount The amount of KUSD user want to mint
*/
function mint(uint kUSDAmount) external checkStart updateReward(msg.sender) {
address payable msgSender = _msgSender();
// update sender's mint time
accountRewardDetails[msgSender].lastMintTime = block.timestamp;
uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD));
require(kMCDPriceMantissa != 0, "Mint: get Kine MCD price zero");
CalculateVars memory vars;
// KUSD has 18 decimals
// KMCD has 18 decimals
// kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18
// so the calculation of equivalent Kine MCD amount is as below
// kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18
// equivalentKMCDAmount = ----------- * ------------------ * 1e18 = -----------------
// 1e18 kMCDPriceMantissa kMCDPriceMantissa
vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa);
// call KMCD contract to borrow Kine MCD for user and stake them
kMCD.borrowBehalf(msgSender, vars.equivalentKMCDAmount);
// mint KUSD to user
kUSD.mint(msgSender, kUSDAmount);
emit Mint(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes());
}
/**
* @notice Burn repay equivalent Kine MCD for user and burn specified amount of KUSD
* Burn will fail if hasn't reach start time.
* @param kUSDAmount The amount of KUSD user want to burn
*/
function burn(uint kUSDAmount) external checkStart afterCooldown(msg.sender) updateReward(msg.sender) {
address msgSender = _msgSender();
// burn user's KUSD
kUSD.burn(msgSender, kUSDAmount);
// calculate equivalent Kine MCD amount to specified amount of KUSD
uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD));
require(kMCDPriceMantissa != 0, "Burn: get Kine MCD price zero");
CalculateVars memory vars;
// KUSD has 18 decimals
// KMCD has 18 decimals
// kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18
// so the calculation of equivalent Kine MCD amount is as below
// kUSDAmount 1e12 * 1e6 kUSDAmount * 1e18
// equivalentKMCDAmount = ----------- * ------------------ * 1e18 = -----------------
// 1e18 kMCDPriceMantissa kMCDPriceMantissa
vars.equivalentKMCDAmount = kUSDAmount.mul(1e18).div(kMCDPriceMantissa);
// call KMCD contract to repay Kine MCD for user
kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount);
emit Burn(msgSender, kUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes());
}
/**
* @notice BurnMax unstake and repay all borrowed Kine MCD for user and burn equivalent KUSD
*/
function burnMax() external checkStart afterCooldown(msg.sender) updateReward(msg.sender) {
address msgSender = _msgSender();
uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD));
require(kMCDPriceMantissa != 0, "BurnMax: get Kine MCD price zero");
CalculateVars memory vars;
// KUSD has 18 decimals
// KMCD has 18 decimals
// kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18
// so the calculation of equivalent KUSD amount is as below
// accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa
// equivalentKUSDAmount = ------------- * ------------------ * 1e18 = ---------------------------------
// 1e18 1e12 * 1e6 1e18
//
// try to unstake all Kine MCD
uint userStakes = accountStakes(msgSender);
vars.equivalentKMCDAmount = userStakes;
vars.equivalentKUSDAmount = userStakes.mul(kMCDPriceMantissa).div(1e18);
// in case user's kUSD is not enough to unstake all mcd, then just burn all kUSD and unstake part of MCD
uint kUSDbalance = kUSD.balanceOf(msgSender);
if (vars.equivalentKUSDAmount > kUSDbalance) {
vars.equivalentKUSDAmount = kUSDbalance;
vars.equivalentKMCDAmount = kUSDbalance.mul(1e18).div(kMCDPriceMantissa);
}
// burn user's equivalent KUSD
kUSD.burn(msgSender, vars.equivalentKUSDAmount);
// call KMCD contract to repay Kine MCD for user
kMCD.repayBorrowBehalf(msgSender, vars.equivalentKMCDAmount);
emit BurnMax(msgSender, vars.equivalentKUSDAmount, vars.equivalentKMCDAmount, accountStakes(msgSender), totalStakes());
}
/**
* @notice Caller liquidates the staker's Kine MCD and seize staker's collateral.
* Liquidate will fail if hasn't reach start time.
* @param staker The staker of Kine MCD to be liquidated.
* @param unstakeKMCDAmount The amount of Kine MCD to unstake.
* @param maxBurnKUSDAmount The max amount limit of KUSD of liquidator to be burned.
* @param kTokenCollateral The market in which to seize collateral from the staker.
*/
function liquidate(address staker, uint unstakeKMCDAmount, uint maxBurnKUSDAmount, address kTokenCollateral, uint minSeizeKToken) external checkStart updateReward(staker) {
address msgSender = _msgSender();
uint kMCDPriceMantissa = KineOracleInterface(controller.getOracle()).getUnderlyingPrice(address(kMCD));
require(kMCDPriceMantissa != 0, "Liquidate: get Kine MCD price zero");
CalculateVars memory vars;
// KUSD has 18 decimals
// KMCD has 18 decimals
// kMCDPriceMantissa is KMCD's price (quoted by KUSD, has 6 decimals) scaled by 1e36 / KMCD's decimals = 1e36 / 1e18 = 1e18
// so the calculation of equivalent KUSD amount is as below
// accountStakes kMCDPriceMantissa accountStakes * kMCDPriceMantissa
// equivalentKUSDAmount = ------------- * ------------------ * 1e18 = ---------------------------------
// 1e18 1e12 * 1e6 1e30
//
vars.equivalentKUSDAmount = unstakeKMCDAmount.mul(kMCDPriceMantissa).div(1e18);
require(maxBurnKUSDAmount >= vars.equivalentKUSDAmount, "Liquidate: reach out max burn KUSD amount limit");
// burn liquidator's KUSD
kUSD.burn(msgSender, vars.equivalentKUSDAmount);
// call KMCD contract to liquidate staker's Kine MCD and seize collateral
kMCD.liquidateBorrowBehalf(msgSender, staker, unstakeKMCDAmount, kTokenCollateral, minSeizeKToken);
emit Liquidate(msgSender, staker, vars.equivalentKUSDAmount, unstakeKMCDAmount, accountStakes(staker), totalStakes());
}
/**
* @notice Show account's staked Kine MCD amount
* @param account The account to be get MCD amount from
*/
function accountStakes(address account) public view returns (uint) {
return kMCD.borrowBalance(account);
}
/// @notice Show total staked Kine MCD amount
function totalStakes() public view returns (uint) {
return kMCD.totalBorrows();
}
/**
* @notice Claim the matured rewards of caller.
* Claim will fail if hasn't reach start time.
*/
function getReward() external checkStart updateReward(msg.sender) {
uint reward = accountRewardDetails[msg.sender].accruedReward;
if (reward > 0) {
uint pastTime = block.timestamp.sub(accountRewardDetails[msg.sender].lastClaimTime);
uint maturedReward = rewardReleasePeriod == 0 ? reward : reward.mul(pastTime).div(rewardReleasePeriod);
if (maturedReward > reward) {
maturedReward = reward;
}
accountRewardDetails[msg.sender].accruedReward = reward.sub(maturedReward);
accountRewardDetails[msg.sender].lastClaimTime = block.timestamp;
kine.safeTransfer(msg.sender, maturedReward);
emit RewardPaid(msg.sender, maturedReward);
}
}
/**
* @notice Notify rewards has been added, trigger a new round of reward period, recalculate reward rate and duration end time.
* If distributor notify rewards before this round duration end time, then the leftover rewards of this round will roll over to
* next round and will be distributed together with new rewards in next round of reward period.
* @param reward How many of rewards has been added for new round of reward period.
*/
function notifyRewardAmount(uint reward) external onlyRewardDistribution updateReward(address(0)) {
if (block.timestamp > startTime) {
if (block.timestamp >= periodFinish) {
// @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range
// which is 2^256 / 10^18
require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow");
rewardRate = reward.div(rewardDuration);
} else {
uint remaining = periodFinish.sub(block.timestamp);
uint leftover = remaining.mul(rewardRate);
// @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range
// which is 2^256 / 10^18
require(reward.add(leftover) < REWARD_OVERFLOW_CHECK, "reward rate will overflow");
rewardRate = reward.add(leftover).div(rewardDuration);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardDuration);
emit RewardAdded(reward);
} else {
// @dev to avoid of rewardPerToken calculation overflow (see https://sips.synthetix.io/sips/sip-77), we check the reward to be inside a properate range
// which is 2^256 / 10^18
require(reward < REWARD_OVERFLOW_CHECK, "reward rate will overflow");
rewardRate = reward.div(rewardDuration);
lastUpdateTime = startTime;
periodFinish = startTime.add(rewardDuration);
emit RewardAdded(reward);
}
}
/**
* @notice Set new reward duration, will start a new round of reward period immediately and recalculate rewardRate.
* @param newRewardDuration New duration of each reward period round.
*/
function _setRewardDuration(uint newRewardDuration) external onlyOwner updateReward(address(0)) {
uint oldRewardDuration = rewardDuration;
rewardDuration = newRewardDuration;
if (block.timestamp > startTime) {
if (block.timestamp >= periodFinish) {
rewardRate = 0;
} else {
uint remaining = periodFinish.sub(block.timestamp);
uint leftover = remaining.mul(rewardRate);
rewardRate = leftover.div(rewardDuration);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardDuration);
} else {
rewardRate = rewardRate.mul(oldRewardDuration).div(rewardDuration);
lastUpdateTime = startTime;
periodFinish = startTime.add(rewardDuration);
}
emit NewRewardDuration(oldRewardDuration, newRewardDuration);
}
/**
* @notice Set new reward release period. The unclaimed rewards will be affected immediately.
* @param newRewardReleasePeriod New release period of how long all earned rewards will be matured each time
* before user claim reward.
*/
function _setRewardReleasePeriod(uint newRewardReleasePeriod) external onlyOwner updateReward(address(0)) {
uint oldRewardReleasePeriod = rewardReleasePeriod;
rewardReleasePeriod = newRewardReleasePeriod;
emit NewRewardReleasePeriod(oldRewardReleasePeriod, newRewardReleasePeriod);
}
function _setCooldownTime(uint newCooldownTime) external onlyOwner {
uint oldCooldown = burnCooldownTime;
burnCooldownTime = newCooldownTime;
emit NewBurnCooldownTime(oldCooldown, newCooldownTime);
}
/**
* @notice Mint KUSD to treasury account to keep on-chain KUSD consist with off-chain trading system
* @param amount The amount of KUSD to mint to treasury
*/
function treasuryMint(uint amount) external onlyTreasury {
kUSD.mint(vault, amount);
emit TreasuryMint(amount);
}
/**
* @notice Burn KUSD from treasury account to keep on-chain KUSD consist with off-chain trading system
* @param amount The amount of KUSD to burn from treasury
*/
function treasuryBurn(uint amount) external onlyTreasury {
kUSD.burn(vault, amount);
emit TreasuryBurn(amount);
}
/**
* @notice Change treasury account to a new one
* @param newTreasury New treasury account address
*/
function _setTreasury(address newTreasury) external onlyOwner {
address oldTreasury = treasury;
treasury = newTreasury;
emit NewTreasury(oldTreasury, newTreasury);
}
/**
* @notice Change vault account to a new one
* @param newVault New vault account address
*/
function _setVault(address newVault) external onlyOwner {
address oldVault = vault;
vault = newVault;
emit NewVault(oldVault, newVault);
}
/**
* @notice Change KMCD contract address to a new one.
* @param newKMCD New KMCD contract address.
*/
function _setKMCD(address newKMCD) external onlyOwner {
address oldKMCD = address(kMCD);
kMCD = IKMCD(newKMCD);
emit NewKMCD(oldKMCD, newKMCD);
}
/**
* @notice Change KUSD contract address to a new one.
* @param newKUSD New KineUSD contract address.
*/
function _setKUSD(address newKUSD) external onlyOwner {
address oldKUSD = address(kUSD);
kUSD = IKineUSD(newKUSD);
emit NewKUSD(oldKUSD, newKUSD);
}
/**
* @notice Change Kine contract address to a new one.
* @param newKine New Kine contract address.
*/
function _setKine(address newKine) external onlyOwner {
address oldKine = address(kine);
kine = IERC20(newKine);
emit NewKine(oldKine, newKine);
}
/**
* @notice Change Kine Controller address to a new one.
* @param newController New Controller contract address.
*/
function _setController(address newController) external onlyOwner {
address oldController = address(controller);
controller = KineControllerInterface(newController);
emit NewController(oldController, newController);
}
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
/**
* @title KineOracleInterface brief abstraction of Price Oracle
*/
interface KineOracleInterface {
/**
* @notice Get the underlying collateral price of given kToken.
* @dev Returned kToken underlying price is scaled by 1e(36 - underlying token decimals)
*/
function getUnderlyingPrice(address kToken) external view returns (uint);
/**
* @notice Post prices of tokens owned by Kine.
* @param messages Signed price data of tokens
* @param signatures Signatures used to recover reporter public key
* @param symbols Token symbols
*/
function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external;
/**
* @notice Post Kine MCD price.
*/
function postMcdPrice(uint mcdPrice) external;
/**
* @notice Get the reporter address.
*/
function reporter() external returns (address);
}
pragma solidity ^0.5.16;
/**
Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Original work from Compound: https://github.com/compound-finance/compound-protocol/blob/master/contracts/ComptrollerInterface.sol
* Modified to work in the Kine system.
* Main modifications:
* 1. removed Comp token related logics.
* 2. removed interest rate model related logics.
* 3. removed error code propagation mechanism to fail fast and loudly
*/
contract KineControllerInterface {
/// @notice Indicator that this is a Controller contract (for inspection)
bool public constant isController = true;
/// @notice oracle getter function
function getOracle() external view returns (address);
/*** Assets You Are In ***/
function enterMarkets(address[] calldata kTokens) external;
function exitMarket(address kToken) external;
/*** Policy Hooks ***/
function mintAllowed(address kToken, address minter, uint mintAmount) external returns (bool, string memory);
function mintVerify(address kToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address kToken, address redeemer, uint redeemTokens) external returns (bool, string memory);
function redeemVerify(address kToken, address redeemer, uint redeemTokens) external;
function borrowAllowed(address kToken, address borrower, uint borrowAmount) external returns (bool, string memory);
function borrowVerify(address kToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address kToken,
address payer,
address borrower,
uint repayAmount) external returns (bool, string memory);
function repayBorrowVerify(
address kToken,
address payer,
address borrower,
uint repayAmount) external;
function liquidateBorrowAllowed(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (bool, string memory);
function liquidateBorrowVerify(
address kTokenBorrowed,
address kTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (bool, string memory);
function seizeVerify(
address kTokenCollateral,
address kTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address kToken, address src, address dst, uint transferTokens) external returns (bool, string memory);
function transferVerify(address kToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address target,
address kTokenBorrowed,
address kTokenCollateral,
uint repayAmount) external view returns (uint);
}
pragma solidity ^0.5.16;
import "./Ownable.sol";
/**
* @title KUSDMinterDelegate
* @author Kine
*/
contract KUSDMinterDelegate is Ownable {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Implementation address
*/
address public implementation;
}
pragma solidity ^0.5.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);
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./Context.sol";
import "./IERC20.sol";
import "./KineSafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using KineSafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./KineSafeMath.sol";
import "./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 KineSafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.0;
import "./Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.5.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.
*/
/**
* Original work from OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.0/contracts/math/SafeMath.sol
* changes we made:
* 1. add two methods that take errorMessage as input parameter
*/
library KineSafeMath {
/**
* @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 on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
* added by Kine
*/
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
* 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 multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
* added by Kine
*/
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.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
|
Calculate account's earned rewards so far. account Which account to be viewed. return Account's earned rewards so far./
|
function earned(address account) public view returns (uint) {
AccountRewardDetail memory detail = accountRewardDetails[account];
uint scaledRewardPerTokenUpdated = detail.rewardPerTokenUpdated;
uint scaledAccruedReward = detail.accruedReward;
for (uint i = detail.scaleParamIndex; i < currentScaleParamIndex; i++) {
scaledRewardPerTokenUpdated = scaledRewardPerTokenUpdated.mul(scaleParams[i]).div(1e18);
scaledAccruedReward = scaledAccruedReward.mul(scaleParams[i]).div(1e18);
}
return accountStakes(account)
.mul(rewardPerToken().sub(scaledRewardPerTokenUpdated))
.div(1e18)
.add(scaledAccruedReward);
}
| 300,519
|
./full_match/44787/0x66bF67f33c577EeE06AB365Fb63cCf3bA36c20E5/sources/contracts/marketMain/MarketMain.sol
|
See {INFTKEYMarketPlaceV1-getTokenBids}./
|
function getTokenBids(uint256 tokenId) external view returns (Interface.Bid[] memory) {
return _selectedMarketPlaceToken.getTokenBids(tokenId);
}
| 13,246,710
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import './ERC2981ContractWideRoyalties.sol';
import "./Registry.sol";
import "hardhat/console.sol";
/// @title contract for ATO
/// @author Olivier Fernandez / Frรฉdรฉric Le Coidic
/// @notice create ERC721 token with IEP2981
contract Ato is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable, ERC2981ContractWideRoyalties {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
address public author; // The address of the author
string public metadata; // The URI of the metadata
uint public max; // The maximum number of copies
bool public set; // True if the tokenURI is set
address public RegistryAddress; // The address of the registry contract
modifier onlyAuthor()
{
require(author == msg.sender, "ONLY_AUTHOR");
_;
}
event Minted(
uint256 indexed nftId,
address indexed author
);
/// @notice constructor
/// @param _name name of ERC721 token
/// @param _symbol symbol of ERC721 token
/// @param _metadata metadata of NFT
/// @param _max maximum mint of NFT
/// @param _royalties percentage (using 2 decimals - 10000 = 100, 0 = 0)
/// @param _Registry addresse of Registry contract
constructor(
string memory _name,
string memory _symbol,
string memory _metadata,
uint _max,
uint _mintNumber,
uint _royalties,
address _Registry)
ERC721(_name, _symbol)
{
author = msg.sender;
max = _max;
setMetadata(_metadata);
RegistryAddress = _Registry;
if (bytes(metadata).length > 0) {
set = true;
if (_mintNumber > _max) {
_mintNumber = _max;
}
mintBatch(_mintNumber);
}
_setRoyalties(_royalties);
// add author and contract to Registry
Registry registry = Registry(RegistryAddress);
registry.addNFT(author, address(this), _max);
}
/// @notice set Metadata of Token
/// @param _metadata metadata of NFT
function setMetadata(string memory _metadata) public onlyAuthor
{
require(!set,"Metadata already set");
metadata = _metadata;
set = true;
}
/// @notice get mint counter value
function getTokenIdCounter() public view returns (uint)
{
return _tokenIdCounter.current();
}
/// @notice mint NFT by batch
/// @param _number number of NFT to mint
function mintBatch(uint _number) public onlyAuthor
{
require(set,"Metadata not set");
uint current = _tokenIdCounter.current();
uint last = current + _number;
require(last <= max, "Maximum NFT already create");
for (uint i = current; i < last; i++) {
_mintNFT();
}
}
/// @notice mint NFT and assigns them to `author`.
/// @notice Emits a {Mint} event.
function _mintNFT() private
{
_tokenIdCounter.increment();
_safeMint(author, _tokenIdCounter.current());
_setTokenURI(_tokenIdCounter.current(), metadata);
emit Minted(_tokenIdCounter.current(), author);
}
/// @dev Sets token royalties
/// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0)
function _setRoyalties(uint256 value) private onlyAuthor
{
require(value <= 10000, 'ERC2981Royalties: Too high');
super._setRoyalties(author, value);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage)
{
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function owner() public view override returns (address) {
return super.owner();
}
function transferOwnership(address newOwner) public override onlyOwner {
super.transferOwnership(newOwner);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, ERC2981ContractWideRoyalties)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
|
mint NFT by batch _number number of NFT to mint
|
function mintBatch(uint _number) public onlyAuthor
{
require(set,"Metadata not set");
uint current = _tokenIdCounter.current();
uint last = current + _number;
require(last <= max, "Maximum NFT already create");
for (uint i = current; i < last; i++) {
_mintNFT();
}
}
| 12,860,265
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.9;
import { Initializable } from '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import { IUniswapV3Pool } from '@uniswap/v3-core-0.8-support/contracts/interfaces/IUniswapV3Pool.sol';
import { IUniswapV3MintCallback } from '@uniswap/v3-core-0.8-support/contracts/interfaces/callback/IUniswapV3MintCallback.sol';
import { IUniswapV3SwapCallback } from '@uniswap/v3-core-0.8-support/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
import { FixedPoint128 } from '@uniswap/v3-core-0.8-support/contracts/libraries/FixedPoint128.sol';
import { FullMath } from '@uniswap/v3-core-0.8-support/contracts/libraries/FullMath.sol';
import { TickMath } from '@uniswap/v3-core-0.8-support/contracts/libraries/TickMath.sol';
import { IVPoolWrapper } from '../../interfaces/IVPoolWrapper.sol';
import { IVQuote } from '../../interfaces/IVQuote.sol';
import { IVToken } from '../../interfaces/IVToken.sol';
import { IVToken } from '../../interfaces/IVToken.sol';
import { IClearingHouse } from '../../interfaces/IClearingHouse.sol';
import { IClearingHouseStructures } from '../../interfaces/clearinghouse/IClearingHouseStructures.sol';
import { AddressHelper } from '../../libraries/AddressHelper.sol';
import { FundingPayment } from '../../libraries/FundingPayment.sol';
import { SimulateSwap } from '../../libraries/SimulateSwap.sol';
import { TickExtended } from '../../libraries/TickExtended.sol';
import { PriceMath } from '../../libraries/PriceMath.sol';
import { SafeCast } from '../../libraries/SafeCast.sol';
import { SignedMath } from '../../libraries/SignedMath.sol';
import { SignedFullMath } from '../../libraries/SignedFullMath.sol';
import { SwapMath } from '../../libraries/SwapMath.sol';
import { UniswapV3PoolHelper } from '../../libraries/UniswapV3PoolHelper.sol';
import { Extsload } from '../../utils/Extsload.sol';
import { UNISWAP_V3_DEFAULT_TICKSPACING, UNISWAP_V3_DEFAULT_FEE_TIER } from '../../utils/constants.sol';
contract VPoolWrapper is IVPoolWrapper, IUniswapV3MintCallback, IUniswapV3SwapCallback, Initializable, Extsload {
using AddressHelper for IVToken;
using FullMath for uint256;
using FundingPayment for FundingPayment.Info;
using SignedMath for int256;
using SignedFullMath for int256;
using PriceMath for uint160;
using SafeCast for uint256;
using SafeCast for uint128;
using SimulateSwap for IUniswapV3Pool;
using TickExtended for IUniswapV3Pool;
using TickExtended for mapping(int24 => TickExtended.Info);
using UniswapV3PoolHelper for IUniswapV3Pool;
IClearingHouse public clearingHouse;
IVToken public vToken;
IVQuote public vQuote;
IUniswapV3Pool public vPool;
// fee paid to liquidity providers, in 1e6
uint24 public liquidityFeePips;
// fee paid to DAO treasury
uint24 public protocolFeePips;
uint256 public accruedProtocolFee;
FundingPayment.Info public fpGlobal;
uint256 public sumFeeGlobalX128;
int256 constant FUNDING_RATE_OVERRIDE_NULL_VALUE = type(int256).max;
int256 public fundingRateOverrideX128;
mapping(int24 => TickExtended.Info) public ticksExtended;
error NotClearingHouse();
error NotGovernance();
error NotUniswapV3Pool();
error InvalidTicks(int24 tickLower, int24 tickUpper);
modifier onlyClearingHouse() {
if (msg.sender != address(clearingHouse)) {
revert NotClearingHouse();
}
_;
}
modifier onlyGovernance() {
if (msg.sender != clearingHouse.governance()) {
revert NotGovernance();
}
_;
}
modifier onlyUniswapV3Pool() {
if (msg.sender != address(vPool)) {
revert NotUniswapV3Pool();
}
_;
}
modifier checkTicks(int24 tickLower, int24 tickUpper) {
if (
tickLower >= tickUpper ||
tickLower < TickMath.MIN_TICK ||
tickUpper > TickMath.MAX_TICK ||
tickLower % UNISWAP_V3_DEFAULT_TICKSPACING != 0 ||
tickUpper % UNISWAP_V3_DEFAULT_TICKSPACING != 0
) revert InvalidTicks(tickLower, tickUpper);
_;
}
/**
PLATFORM FUNCTIONS
*/
function initialize(InitializeVPoolWrapperParams calldata params) external initializer {
clearingHouse = params.clearingHouse;
vToken = params.vToken;
vQuote = params.vQuote;
vPool = params.vPool;
liquidityFeePips = params.liquidityFeePips;
protocolFeePips = params.protocolFeePips;
fundingRateOverrideX128 = type(int256).max;
// initializes the funding payment state by zeroing the funding payment for time 0 to blockTimestamp
fpGlobal.update({
vTokenAmount: 0,
liquidity: 1,
blockTimestamp: _blockTimestamp(),
virtualPriceX128: 1,
fundingRateX128: 0 // causes zero funding payment
});
}
function collectAccruedProtocolFee() external onlyClearingHouse returns (uint256 accruedProtocolFeeLast) {
accruedProtocolFeeLast = accruedProtocolFee - 1;
accruedProtocolFee = 1;
emit AccruedProtocolFeeCollected(accruedProtocolFeeLast);
}
/// @notice Update the global funding state, from clearing house
/// @dev Done when clearing house is paused or unpaused, to prevent funding payments from being received
/// or paid when clearing house is in paused mode.
function updateGlobalFundingState(bool useZeroFundingRate) public onlyClearingHouse {
(int256 fundingRateX128, uint256 virtualPriceX128) = getFundingRateAndVirtualPrice();
fpGlobal.update({
vTokenAmount: 0,
liquidity: 1,
blockTimestamp: _blockTimestamp(),
virtualPriceX128: virtualPriceX128,
fundingRateX128: useZeroFundingRate ? int256(0) : fundingRateX128
});
}
/**
ADMIN FUNCTIONS
*/
function setLiquidityFee(uint24 liquidityFeePips_) external onlyGovernance {
liquidityFeePips = liquidityFeePips_;
emit LiquidityFeeUpdated(liquidityFeePips_);
}
function setProtocolFee(uint24 protocolFeePips_) external onlyGovernance {
protocolFeePips = protocolFeePips_;
emit ProtocolFeeUpdated(protocolFeePips_);
}
function setFundingRateOverride(int256 fundingRateOverrideX128_) external onlyGovernance {
fundingRateOverrideX128 = fundingRateOverrideX128_;
emit FundingRateOverrideUpdated(fundingRateOverrideX128_);
}
/**
EXTERNAL UTILITY METHODS
*/
/// @notice Swap vToken for vQuote, or vQuote for vToken
/// @param swapVTokenForVQuote: The direction of the swap, true for vToken to vQuote, false for vQuote to vToken
/// @param amountSpecified: The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96: The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap.
/// @return swapResult swap return values, which contain the execution details of the swap
function swap(
bool swapVTokenForVQuote, // zeroForOne
int256 amountSpecified,
uint160 sqrtPriceLimitX96
) public onlyClearingHouse returns (SwapResult memory swapResult) {
bool exactIn = amountSpecified >= 0;
if (sqrtPriceLimitX96 == 0) {
sqrtPriceLimitX96 = swapVTokenForVQuote ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1;
}
swapResult.amountSpecified = amountSpecified;
SwapMath.beforeSwap(
exactIn,
swapVTokenForVQuote,
UNISWAP_V3_DEFAULT_FEE_TIER,
liquidityFeePips,
protocolFeePips,
swapResult
);
{
SimulateSwap.Cache memory cache;
cache.tickSpacing = UNISWAP_V3_DEFAULT_TICKSPACING;
cache.fee = UNISWAP_V3_DEFAULT_FEE_TIER;
(int256 fundingRateX128, uint256 virtualPriceX128) = getFundingRateAndVirtualPrice();
_writeCacheExtraValues(cache, virtualPriceX128, fundingRateX128);
// simulate swap and update our tick states
(int256 vTokenIn_simulated, int256 vQuoteIn_simulated, SimulateSwap.State memory state) = vPool
.simulateSwap(swapVTokenForVQuote, swapResult.amountSpecified, sqrtPriceLimitX96, cache, _onSwapStep);
// store prices for the simulated swap in the swap result
swapResult.sqrtPriceX96Start = cache.sqrtPriceX96Start;
swapResult.sqrtPriceX96End = state.sqrtPriceX96;
// execute actual swap on uniswap
(swapResult.vTokenIn, swapResult.vQuoteIn) = vPool.swap(
address(this),
swapVTokenForVQuote,
swapResult.amountSpecified,
sqrtPriceLimitX96,
''
);
// simulated swap should be identical to actual swap
assert(vTokenIn_simulated == swapResult.vTokenIn && vQuoteIn_simulated == swapResult.vQuoteIn);
}
SwapMath.afterSwap(
exactIn,
swapVTokenForVQuote,
UNISWAP_V3_DEFAULT_FEE_TIER,
liquidityFeePips,
protocolFeePips,
swapResult
);
// record the protocol fee, for withdrawal in future
accruedProtocolFee += swapResult.protocolFees;
// burn the tokens received from the swap
_vBurn();
emit Swap(swapResult);
}
function mint(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
)
external
onlyClearingHouse
checkTicks(tickLower, tickUpper)
returns (
uint256 vTokenPrincipal,
uint256 vQuotePrincipal,
WrapperValuesInside memory wrapperValuesInside
)
{
// records the funding payment for last updated timestamp to blockTimestamp using current price difference
_updateGlobalFundingState();
wrapperValuesInside = _updateTicks(tickLower, tickUpper, liquidity.toInt128(), vPool.tickCurrent());
(uint256 _amount0, uint256 _amount1) = vPool.mint({
recipient: address(this),
tickLower: tickLower,
tickUpper: tickUpper,
amount: liquidity,
data: ''
});
vTokenPrincipal = _amount0;
vQuotePrincipal = _amount1;
}
function burn(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
)
external
onlyClearingHouse
checkTicks(tickLower, tickUpper)
returns (
uint256 vTokenPrincipal,
uint256 vQuotePrincipal,
WrapperValuesInside memory wrapperValuesInside
)
{
// records the funding payment for last updated timestamp to blockTimestamp using current price difference
_updateGlobalFundingState();
wrapperValuesInside = _updateTicks(tickLower, tickUpper, -liquidity.toInt128(), vPool.tickCurrent());
(uint256 _amount0, uint256 _amount1) = vPool.burn({
tickLower: tickLower,
tickUpper: tickUpper,
amount: liquidity
});
vTokenPrincipal = _amount0;
vQuotePrincipal = _amount1;
_collect(tickLower, tickUpper);
}
/**
UNISWAP V3 POOL CALLBACkS
*/
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata
) external virtual onlyUniswapV3Pool {
if (amount0Delta > 0) {
IVToken(vPool.token0()).mint(address(vPool), uint256(amount0Delta));
}
if (amount1Delta > 0) {
IVToken(vPool.token1()).mint(address(vPool), uint256(amount1Delta));
}
}
function uniswapV3MintCallback(
uint256 vTokenAmount,
uint256 vQuoteAmount,
bytes calldata
) external override onlyUniswapV3Pool {
if (vQuoteAmount > 0) vQuote.mint(msg.sender, vQuoteAmount);
if (vTokenAmount > 0) vToken.mint(msg.sender, vTokenAmount);
}
/**
VIEW METHODS
*/
function getFundingRateAndVirtualPrice() public view returns (int256 fundingRateX128, uint256 virtualPriceX128) {
int256 _fundingRateOverrideX128 = fundingRateOverrideX128;
bool shouldUseActualPrices = _fundingRateOverrideX128 == FUNDING_RATE_OVERRIDE_NULL_VALUE;
uint32 poolId = vToken.truncate();
virtualPriceX128 = clearingHouse.getVirtualTwapPriceX128(poolId);
if (shouldUseActualPrices) {
// uses actual price to calculate funding rate
uint256 realPriceX128 = clearingHouse.getRealTwapPriceX128(poolId);
fundingRateX128 = FundingPayment.getFundingRate(realPriceX128, virtualPriceX128);
} else {
// uses funding rate override
fundingRateX128 = _fundingRateOverrideX128;
}
}
function getSumAX128() external view returns (int256) {
return fpGlobal.sumAX128;
}
function getExtrapolatedSumAX128() public view returns (int256) {
(int256 fundingRateX128, uint256 virtualPriceX128) = getFundingRateAndVirtualPrice();
return
FundingPayment.extrapolatedSumAX128(
fpGlobal.sumAX128,
fpGlobal.timestampLast,
_blockTimestamp(),
fundingRateX128,
virtualPriceX128
);
}
function getValuesInside(int24 tickLower, int24 tickUpper)
public
view
checkTicks(tickLower, tickUpper)
returns (WrapperValuesInside memory wrapperValuesInside)
{
(, int24 currentTick, , , , , ) = vPool.slot0();
FundingPayment.Info memory _fpGlobal = fpGlobal;
wrapperValuesInside.sumAX128 = _fpGlobal.sumAX128;
(
wrapperValuesInside.sumBInsideX128,
wrapperValuesInside.sumFpInsideX128,
wrapperValuesInside.sumFeeInsideX128
) = ticksExtended.getTickExtendedStateInside(tickLower, tickUpper, currentTick, _fpGlobal, sumFeeGlobalX128);
}
function getExtrapolatedValuesInside(int24 tickLower, int24 tickUpper)
external
view
returns (WrapperValuesInside memory wrapperValuesInside)
{
(, int24 currentTick, , , , , ) = vPool.slot0();
FundingPayment.Info memory _fpGlobal = fpGlobal;
///@dev update sumA and sumFP to extrapolated values according to current timestamp
_fpGlobal.sumAX128 = getExtrapolatedSumAX128();
_fpGlobal.sumFpX128 = FundingPayment.extrapolatedSumFpX128(
fpGlobal.sumAX128,
fpGlobal.sumBX128,
fpGlobal.sumFpX128,
_fpGlobal.sumAX128
);
wrapperValuesInside.sumAX128 = _fpGlobal.sumAX128;
(
wrapperValuesInside.sumBInsideX128,
wrapperValuesInside.sumFpInsideX128,
wrapperValuesInside.sumFeeInsideX128
) = ticksExtended.getTickExtendedStateInside(tickLower, tickUpper, currentTick, _fpGlobal, sumFeeGlobalX128);
}
/**
INTERNAL HELPERS
*/
function _collect(int24 tickLower, int24 tickUpper) internal {
// (uint256 amount0, uint256 amount1) =
vPool.collect({
recipient: address(this),
tickLower: tickLower,
tickUpper: tickUpper,
amount0Requested: type(uint128).max,
amount1Requested: type(uint128).max
});
_vBurn();
}
function _readCacheExtraValues(SimulateSwap.Cache memory cache)
private
pure
returns (uint256 virtualPriceX128, int256 fundingRateX128)
{
uint256 value1 = cache.value1;
uint256 value2 = cache.value2;
assembly {
virtualPriceX128 := value1
fundingRateX128 := value2
}
}
function _writeCacheExtraValues(
SimulateSwap.Cache memory cache,
uint256 virtualPriceX128,
int256 fundingRateX128
) private pure {
uint256 value1;
uint256 value2;
assembly {
value1 := virtualPriceX128
value2 := fundingRateX128
}
cache.value1 = value1;
cache.value2 = value2;
}
function _onSwapStep(
bool swapVTokenForVQuote,
SimulateSwap.Cache memory cache,
SimulateSwap.State memory state,
SimulateSwap.Step memory step
) internal {
// these vQuote and vToken amounts are zero fee swap amounts (fee collected by uniswaop is ignored and burned later)
(uint256 vTokenAmount, uint256 vQuoteAmount) = swapVTokenForVQuote
? (step.amountIn, step.amountOut)
: (step.amountOut, step.amountIn);
// here, vQuoteAmount == swap amount
(uint256 liquidityFees, ) = SwapMath.calculateFees(
vQuoteAmount.toInt256(),
SwapMath.AmountTypeEnum.ZERO_FEE_VQUOTE_AMOUNT,
liquidityFeePips,
protocolFeePips
);
// vQuote amount with fees
// vQuoteAmount = _includeFees(
// vQuoteAmount,
// liquidityFees + protocolFees,
// swapVTokenForVQuote ? IncludeFeeEnum.SUBTRACT_FEE : IncludeFeeEnum.ADD_FEE
// );
if (state.liquidity > 0 && vTokenAmount > 0) {
(uint256 virtualPriceX128, int256 fundingRateX128) = _readCacheExtraValues(cache);
fpGlobal.update({
vTokenAmount: swapVTokenForVQuote ? vTokenAmount.toInt256() : -vTokenAmount.toInt256(), // when trader goes long, LP goes short
liquidity: state.liquidity,
blockTimestamp: _blockTimestamp(),
virtualPriceX128: virtualPriceX128,
fundingRateX128: fundingRateX128
});
sumFeeGlobalX128 += liquidityFees.mulDiv(FixedPoint128.Q128, state.liquidity);
}
// if we have reached the end price of tick
if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {
// if the tick is initialized, run the tick transition
if (step.initialized) {
ticksExtended.cross(step.tickNext, fpGlobal, sumFeeGlobalX128);
}
}
}
/// @notice Update global funding payment, by getting prices from Clearing House
function _updateGlobalFundingState() internal {
(int256 fundingRateX128, uint256 virtualPriceX128) = getFundingRateAndVirtualPrice();
fpGlobal.update({
vTokenAmount: 0,
liquidity: 1,
blockTimestamp: _blockTimestamp(),
virtualPriceX128: virtualPriceX128,
fundingRateX128: fundingRateX128
});
}
function _updateTicks(
int24 tickLower,
int24 tickUpper,
int128 liquidityDelta,
int24 tickCurrent
) private returns (WrapperValuesInside memory wrapperValuesInside) {
FundingPayment.Info memory _fpGlobal = fpGlobal; // SLOAD
uint256 _sumFeeGlobalX128 = sumFeeGlobalX128;
// if we need to update the ticks, do it
bool flippedLower;
bool flippedUpper;
if (liquidityDelta != 0) {
flippedLower = ticksExtended.update(
tickLower,
tickCurrent,
liquidityDelta,
_fpGlobal.sumAX128,
_fpGlobal.sumBX128,
_fpGlobal.sumFpX128,
_sumFeeGlobalX128,
vPool
);
flippedUpper = ticksExtended.update(
tickUpper,
tickCurrent,
liquidityDelta,
_fpGlobal.sumAX128,
_fpGlobal.sumBX128,
_fpGlobal.sumFpX128,
_sumFeeGlobalX128,
vPool
);
}
wrapperValuesInside = getValuesInside(tickLower, tickUpper);
// clear any tick data that is no longer needed
if (liquidityDelta < 0) {
if (flippedLower) {
ticksExtended.clear(tickLower);
}
if (flippedUpper) {
ticksExtended.clear(tickUpper);
}
}
}
function _vBurn() internal {
uint256 vQuoteBal = vQuote.balanceOf(address(this));
if (vQuoteBal > 0) {
vQuote.burn(vQuoteBal);
}
uint256 vTokenBal = vToken.balanceOf(address(this));
if (vTokenBal > 0) {
vToken.burn(vTokenBal);
}
}
// used to set time in tests
function _blockTimestamp() internal view virtual returns (uint48) {
return uint48(block.timestamp);
}
}
|
uses actual price to calculate funding rate uses funding rate override
|
function getFundingRateAndVirtualPrice() public view returns (int256 fundingRateX128, uint256 virtualPriceX128) {
int256 _fundingRateOverrideX128 = fundingRateOverrideX128;
bool shouldUseActualPrices = _fundingRateOverrideX128 == FUNDING_RATE_OVERRIDE_NULL_VALUE;
uint32 poolId = vToken.truncate();
virtualPriceX128 = clearingHouse.getVirtualTwapPriceX128(poolId);
if (shouldUseActualPrices) {
uint256 realPriceX128 = clearingHouse.getRealTwapPriceX128(poolId);
fundingRateX128 = FundingPayment.getFundingRate(realPriceX128, virtualPriceX128);
fundingRateX128 = _fundingRateOverrideX128;
}
}
| 13,044,067
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
import '../nft/ApexaNFT.sol';
import '../utils/Whitelist.sol';
contract NFTSale is Whitelist {
using Address for address;
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private NftId;
ApexaNFT public nftContract;
mapping(address => Counters.Counter) public userPurchaseCounter;
uint256 public purchaseLimit;
bool public isSaleEnabled;
uint256 public price;
string public placeholderURI;
event Sold(uint256 _nftId, address _buyer, uint256 _price);
event EnableSale(bool _isSaleEnabled);
constructor(
address _nftAddress,
uint256 _purchaseLimit,
uint256 _price,
bool _checkForWhitelist,
string memory _placeholderURI
) {
require(_nftAddress.isContract(), '_nftAddress must be a contract');
nftContract = ApexaNFT(_nftAddress);
purchaseLimit = _purchaseLimit;
price = _price;
checkForWhitelist = _checkForWhitelist;
placeholderURI = _placeholderURI;
}
/**
* @notice - Enable/Disable Sales
* @dev - callable only by owner
*
* @param _isSaleEnabled - enable? sales
*/
function setSaleEnabled(bool _isSaleEnabled) public onlyOwner {
isSaleEnabled = _isSaleEnabled;
emit EnableSale(isSaleEnabled);
}
function setPlaceholderURI(string memory _placeholderURI) external onlyAdmin {
placeholderURI = _placeholderURI;
}
/**
* @notice - Set Placeholder URI
* @dev - callable only by owner
*
* @param _price - price of NFTs
*/
function setPrice(uint256 _price) public onlyOwner {
price = _price;
}
function _purchase() internal {
address buyer = _msgSender();
require(userPurchaseCounter[buyer].current() < purchaseLimit, 'Purchase amount exceeds the limit per wallet');
uint256 _nftId = nftContract.mint(buyer, placeholderURI);
userPurchaseCounter[buyer].increment();
emit Sold(_nftId, buyer, price);
}
/**
* Purchase nftContract
*
*/
function purchase() external payable onlyDuringSale onlyWhitelisted {
require(msg.value == price, 'Insufficient or excess funds');
_purchase();
}
/**
* Purchase Batch of NFTs
*
* @param numberOfTokens - TokenIds to be purchased
*/
function batchPurchase(uint256 numberOfTokens) external payable onlyDuringSale onlyWhitelisted {
require(msg.value == price * numberOfTokens, 'Insufficient or excess funds');
for (uint256 i = 0; i < numberOfTokens; i++) {
_purchase();
}
}
/**
* Withdraw any ETH funds on contract
*/
function withdrawETH() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
function withdrawFunds(
address tokenAddress,
uint256 amount,
address wallet
) external onlyOwner {
IERC20(tokenAddress).transfer(wallet, amount);
}
modifier onlyDuringSale() {
require(isSaleEnabled, 'Sale is not enabled');
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
import '../utils/AccessProtected.sol';
contract ApexaNFT is ERC721('Apex Athletes', 'AA'), AccessProtected {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private tokenIds;
string private _baseURI;
uint256 private _revealedTill;
uint256 public cap;
event SetCap(uint256 _cap);
constructor(uint256 _cap) {
setCap(_cap);
}
/**
* @notice - Mint NFT
* @dev - callable only by admin
*
* @param recipient - mint to
* @param URI - uri of the NFT
*/
function mint(address recipient, string memory URI) external onlyAdmin returns (uint256) {
tokenIds.increment();
uint256 newTokenId = tokenIds.current();
require(newTokenId <= cap, 'NFT cap exceeded');
_mint(recipient, newTokenId);
_setTokenURI(newTokenId, URI);
return newTokenId;
}
/**
* @notice - Set URI for token
* @dev - callable only by admin
*
* @param tokenId - Token ID of NFT
* @param _tokenURI - URI to set
*/
function setURI(uint256 tokenId, string memory _tokenURI) external onlyAdmin {
_setTokenURI(tokenId, _tokenURI);
}
function setCap(uint256 _cap) public onlyOwner {
cap = _cap;
emit SetCap(_cap);
}
/**
* @notice - Set URI for token batch
* @dev - callable only by admin
*
* @param _tokenIds - Token IDs of NFTs
* @param tokenURIs - URIs to set
*/
function setBatchURI(uint256[] memory _tokenIds, string[] memory tokenURIs) external onlyAdmin {
require(_tokenIds.length == tokenURIs.length, 'Length mismatch');
for (uint256 i = 0; i < _tokenIds.length; i++) {
_setTokenURI(_tokenIds[i], tokenURIs[i]);
}
}
function baseURIForReveals() public view virtual returns (string memory) {
return _baseURI;
}
function setBaseURI(string memory __baseURI) external onlyAdmin {
_baseURI = __baseURI;
}
function setRevealedTill(uint256 __revealedTill) external onlyAdmin {
_revealedTill = __revealedTill;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token');
if (tokenId > _revealedTill || bytes(_baseURI).length == 0) {
return super.tokenURI(tokenId);
}
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
function setTokenURIBatch(uint256[] memory _tokenIds, string[] memory tokenURIs) external onlyAdmin {
require(_tokenIds.length == tokenURIs.length, 'Length mismatch');
for (uint256 i = 0; i < _tokenIds.length; i++) {
_setTokenURI(_tokenIds[i], tokenURIs[i]);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;
import "./AccessProtected.sol";
abstract contract Whitelist is AccessProtected {
mapping(address => bool) public whitelisted;
mapping(address => bool) public blacklisted;
bool public checkForWhitelist;
event Whitelisted(address indexed _addr, bool enabled);
event Blacklisted(address indexed _addr, bool enabled);
event SetWhitelistEnabled(bool enabled);
function setWhitelistEnabled(bool enabled) public onlyAdmin {
checkForWhitelist = enabled;
emit SetWhitelistEnabled(enabled);
}
function _whitelist(address user, bool enabled) internal {
whitelisted[user] = enabled;
emit Whitelisted(user, enabled);
}
function whitelist(address user, bool enabled) external onlyAdmin {
_whitelist(user, enabled);
}
function whitelistBatch(address[] memory users, bool[] memory enabled)
external
onlyAdmin
{
require(
users.length == enabled.length,
"Length of users and enabled must match"
);
for (uint256 i = 0; i < users.length; i++) {
_whitelist(users[i], enabled[i]);
}
}
function _blacklist(address user, bool enabled) internal {
blacklisted[user] = enabled;
emit Blacklisted(user, enabled);
}
function blacklist(address user, bool enabled) external onlyAdmin {
_blacklist(user, enabled);
}
function blacklistBatch(address[] memory users, bool[] memory enabled)
external
onlyAdmin
{
require(
users.length == enabled.length,
"Length of users and enabled must match"
);
for (uint256 index = 0; index < users.length; index++) {
_blacklist(users[index], enabled[index]);
}
}
modifier onlyWhitelisted() {
require(
checkForWhitelist == false || whitelisted[msg.sender] == true,
"User is not whitelisted"
);
require(blacklisted[msg.sender] == false, "User is blacklisted");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
abstract contract AccessProtected is Context, Ownable {
mapping(address => bool) internal _admins; // user address => admin? mapping
event AdminAccessSet(address _admin, bool _enabled);
/**
* @notice Set Admin Access
*
* @param admin - Address of Admin
* @param enabled - Enable/Disable Admin Access
*/
function setAdmin(address admin, bool enabled) external onlyOwner {
_admins[admin] = enabled;
emit AdminAccessSet(admin, enabled);
}
/**
* @notice Check Admin Access
*
* @param admin - Address of Admin
* @return whether user has admin access
*/
function isAdmin(address admin) public view returns (bool) {
return _admins[admin];
}
/**
* Throws if called by any account other than the Admin.
*/
modifier onlyAdmin() {
require(
_admins[_msgSender()] || _msgSender() == owner(),
"Caller does not have Admin Access"
);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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;
}
}
|
Purchase nftContract/
|
function purchase() external payable onlyDuringSale onlyWhitelisted {
require(msg.value == price, 'Insufficient or excess funds');
_purchase();
}
| 14,860,117
|
./partial_match/1/0xA17b1712dBA02a7Ba477b5b161Cc526BEd404b66/sources/Axe.sol
|
Maximum tx size and wallet size exclude from paying fees or having max transaction amount
|
constructor() ERC20("Axe", "AXE") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 0;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 0;
uint256 _sellDevFee = 1;
uint256 totalSupply = 100000000 * 10 ** _decimals;
maxTransactionAmount = totalSupply * 55 / 10000;
maxWallet = totalSupply * 55 / 10000;
swapTokensAtAmount = totalSupply * 1 / 10000;
buyMarketingFee = _buyMarketingFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 4,121,224
|
pragma solidity ^0.4.24;
contract Token {
/* 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);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
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;
}
}
contract StandardToken is Token {
uint256 constant MAX_UINT256 = 2**256 - 1;
bool transferEnabled = false;
function transfer(address _to, uint256 _value) public returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[msg.sender] >= _value);
require(transferEnabled);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
require(transferEnabled);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) view public returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract AWAToken is StandardToken {
using SafeMath for uint;
// UM
uint8 public constant decimals = 6;
uint256 public totalSupply = 500000000*10**6;
string public constant symbol = "AWA";
string public constant name = "AWA Token";
// Inited in constructor
address public contractOwner; // Can stop the allocation of delayed tokens and can allocate delayed tokens.
address public futureOwner;
// Constructor
// Sets the contractOwner for the onlyOwner modifier
// Sets the public values in the ERC20 standard token
// Opens the delayed allocation window.
// can pre-allocate balances for an array of _accounts
function AWAToken() public {
balances[0xb604312C372FbC942B56151BedD76435ECBd7666] = totalSupply;
contractOwner = 0xb604312C372FbC942B56151BedD76435ECBd7666;
transferEnabled = true;
}
// Called by the token owner to unblock transfers
function enableTransfers() onlyOwner public {
transferEnabled = true;
}
// Called by the token owner to block transfers
function disableTransfers() onlyOwner public {
transferEnabled = false;
}
modifier onlyOwner() {
require(msg.sender == contractOwner);
_;
}
//Distory token left for token sales
function destroyToken() public onlyOwner{
balances[msg.sender] = 0;
}
// Makes sure that the ownership is only changed by the owner
function transferOwnership(address _newOwner) public onlyOwner {
// Makes sure that the contract will have an owner
require(_newOwner != address(0));
futureOwner = _newOwner;
}
function claimOwnership() public {
require(msg.sender == futureOwner);
contractOwner = msg.sender;
futureOwner = address(0);
}
}
|
same as above. Replace this line with the following if you want to protect against wrapping uints.require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);
|
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
require(transferEnabled);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
| 2,209,371
|
pragma solidity ^0.5.0;
contract Administrable {
address private owner;
address[] private admins;
mapping(address => bool) public isAdmin;
/**
* Constructor of the contract
* @param _admins addresses of accounts allowed to administrate the contract
*/
constructor(address[] memory _admins) public {
owner = msg.sender;
for (uint i = 0; i < _admins.length; i++) {
isAdmin[_admins[i]] = true;
}
isAdmin[msg.sender] = true;
admins = _admins;
}
/**
* Require sender to be the owner of the contract to continue the execution
*/
modifier onlyOwner() {
require(msg.sender == owner, "only owner can perform this operation");
_;
}
/**
* Require sender to be an admin of the contract to continue the execution
*/
modifier onlyAdmin() {
require(
isAdmin[msg.sender],
"only a valid admin can perform this operation"
);
_;
}
}
contract EmergencyStoppable {
bool private stopped = false;
mapping(address => bool) private isStopper;
/**
* Constructor of the contract
* @param stoppers allowed accounts to stop/start the contract
*/
constructor(address[] memory stoppers) public {
for (uint i = 0; i < stoppers.length; i++) {
isStopper[stoppers[i]] = true;
}
isStopper[msg.sender] = true;
}
/**
* Require only an allowed address to perform an action
*/
modifier onlyStopper() {
require(
isStopper[msg.sender] == true,
"only autorized stoppers can perform this operation"
);
_;
}
/**
* This modifier requires that the contract IS NOT STOPPED to continue
* the execution of the function
*/
modifier stopInEmergency {
require(
!stopped,
"This action cant be performed at the moment"
);
_;
}
/**
* This modifier requires that the contract IS STOPPED to continue
* the execution of the function
*/
modifier onlyInEmergency {
require(stopped, "This action can only be performed in an emergency");
_;
}
/**
* Stops the contract. Only functions not required to be stopped in
* emergency can continue the execution
*/
function stop() onlyStopper public {
stopped = true;
}
/**
* Starts the contract. All functions but required to execute only in
* emergency continue the execution
*/
function start() onlyStopper public {
stopped = false;
}
}
contract Marketplace is Administrable, EmergencyStoppable {
mapping(address => bool) public storeOwners;
mapping(address => uint[]) public ownerStorefrontIds;
mapping(address => uint) private balances;
struct Storefront {
uint id;
string name;
address storeOwner;
uint[] skus;
}
uint private storefrontsCount;
mapping(uint => Storefront) private storefronts;
struct Product {
uint sku;
string name;
uint count;
uint price;
uint storefrontId;
uint indexInStorefront;
}
uint private skuCount;
mapping(uint => Product) private products;
/**
* Constructor of the contract
* @param _admins addresses of the admins of the Marketplace contract
*/
constructor(address[] memory _admins)
Administrable(_admins)
EmergencyStoppable(_admins)
public
{
}
modifier onlyActiveOwner() {
require(storeOwners[msg.sender]);
_;
}
/**
* Adds a new storefront owner
* @param storeOwner the address of the new store owner
*/
function addStoreOwner(address storeOwner) external onlyAdmin {
require(!storeOwners[storeOwner], "Owner already exists");
storeOwners[storeOwner] = true;
}
/**
* Adds a new storefront
* @param name the name of the new storefront
* @return the ID of the new storefront
*/
function addStorefront(string calldata name)
external
onlyActiveOwner
returns (uint)
{
require(
storefrontsCount != ((2**256) - 1),
"No more storefronts can be added"
);
storefrontsCount++;
ownerStorefrontIds[msg.sender].push(storefrontsCount);
storefronts[storefrontsCount].id = storefrontsCount;
storefronts[storefrontsCount].name = name;
storefronts[storefrontsCount].storeOwner = msg.sender;
return storefrontsCount;
}
/**
* Gets storefront ID, name and list of product SKUs
* @param _id the ID of the storefront information to retrieve
* @return ID, name and SKU array of the storefront
*/
function getStorefront(uint _id)
external
view
returns (uint id, string memory name, uint[] memory skus)
{
id = storefronts[_id].id;
name = storefronts[_id].name;
skus = storefronts[_id].skus;
}
/**
* Gets the amount of storefronts owned by an store owner
* @param storeOwner the address of the store owner count required
* @return the amount of storefronts of the specified store owner
*/
function getOwnerStorefrontCount(address storeOwner)
external
view
returns (uint)
{
return ownerStorefrontIds[storeOwner].length;
}
/**
* @return the total amount of all storefronts of all owners
*/
function getStorefrontCount() external view returns (uint) {
return storefrontsCount;
}
/**
* Adds a new product to a storefront
* @param _storefrontId the storefront where to add the product
* @param name name of the new product
* @param count amount of available products
* @param price cost in Wei of the product
* @return the ID of the new product
*/
function addProduct(
uint _storefrontId,
string calldata name,
uint count,
uint price
)
external
onlyActiveOwner
returns (uint)
{
require(storefronts[_storefrontId].storeOwner == msg.sender);
require(price > 0);
require(
skuCount != ((2**256) - 1),
"No more products can be added"
);
skuCount++;
products[skuCount].storefrontId = _storefrontId;
products[skuCount].sku = skuCount;
products[skuCount].name = name;
products[skuCount].price = price;
products[skuCount].count = count;
products[skuCount].indexInStorefront = storefronts[_storefrontId].skus.push(skuCount) - 1;
return skuCount;
}
/**
* Gets the details of a product
* @param _sku the SKU of the product required
* @return SKU, name, price and storefront ID of the product
*/
function getProduct(uint _sku)
external
view
returns (
uint sku,
string memory name,
uint price,
uint count,
uint storefrontId
)
{
require(products[_sku].sku != 0, "Product does not exist");
sku = products[_sku].sku;
name = products[_sku].name;
price = products[_sku].price;
count = products[_sku].count;
storefrontId = products[_sku].storefrontId;
}
/**
* Deletes a product
* @param _sku the SKU of the product to remove
*/
function deleteProduct(uint _sku) external onlyActiveOwner {
require(
storefronts[products[_sku].storefrontId].storeOwner == msg.sender
);
// Storefront of the product to delete
uint storefrontId = products[_sku].storefrontId;
// Index of the product to delete in storefront's SKUs array
uint index = products[_sku].indexInStorefront;
// Length of the storefront's SKU array
uint skusLength = storefronts[storefrontId].skus.length;
require(skusLength > 0, "Storefront's SKU list is invalid");
// For the array of SKUs in storefront we need to move the last element
// of the array to the index of the product beign removed
uint lastProductIndex;
uint lastProductSku;
if (skusLength > 1) {
// Get the last product index
lastProductIndex = storefronts[storefrontId].skus[skusLength - 1];
// Copy it to the index of the product that is being removed
// from the storefront
storefronts[storefrontId].skus[index] = lastProductIndex;
// Get the replacing product SKU
lastProductSku = storefronts[storefrontId].skus[index];
// Update products indexInStorefront to its new index in storefornt
// SKUs array
products[lastProductSku].indexInStorefront = index;
}
// Delete preduct from mapping
delete products[_sku];
// Remove last product index (already moved to its new place) by
// decrementing storefront SKUs array length by one
storefronts[storefrontId].skus.length--;
}
/**
* Updates product price
* @param _sku the SKU of the product to update
* @param price the new price of the product
*/
function updateProductPrice(uint _sku, uint price)
external
onlyActiveOwner
{
require(
storefronts[products[_sku].storefrontId].storeOwner == msg.sender
);
products[_sku].price = price;
}
/**
* Updates product count
* @param _sku the SKU of the product to update
* @param count the new count of the product
*/
function updateProductCount(uint _sku, uint count)
external
onlyActiveOwner
{
require(
storefronts[products[_sku].storefrontId].storeOwner == msg.sender
);
products[_sku].count = count;
}
/**
* Buy a product, incremente store owner's balance by price and quantity,
* decrement products count by quantity
* @param _sku the SKU of the product being bought
* @param quantity the desired amount of the product
*/
function buyProduct(uint _sku, uint quantity)
external
payable
stopInEmergency
{
require(quantity > 0);
require(products[_sku].count >= quantity);
require(products[_sku].price * quantity <= msg.value);
Product memory product = products[_sku];
Storefront memory storefront = storefronts[product.storefrontId];
balances[storefront.storeOwner] += products[_sku].price * quantity;
products[_sku].count -= quantity;
uint toRefund = msg.value - products[_sku].price * quantity;
if (toRefund > 0) {
msg.sender.transfer(toRefund);
}
}
/**
* Get the balance of the sender (it has to be a store owner)
* @return the balance of the sender
*/
function balance() external view onlyActiveOwner returns(uint) {
return balances[msg.sender];
}
/**
* Withdraw an amount of ether from it's balance (it has to be a store owner)
* @param amount the amount of ether in Wei to withdraw
*/
function withdraw(uint amount) external onlyActiveOwner stopInEmergency {
require(
amount <= balances[msg.sender],
"You dont have enough founds to perform this operation"
);
balances[msg.sender] -= amount;
msg.sender.transfer(amount);
}
}
|
Updates product price _sku the SKU of the product to update price the new price of the product/
|
function updateProductPrice(uint _sku, uint price)
external
onlyActiveOwner
{
require(
storefronts[products[_sku].storefrontId].storeOwner == msg.sender
);
products[_sku].price = price;
}
| 1,080,129
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "../Token/ERC20/IERC20.sol";
// TODO. Maรฑana comentar todas las funciones...
contract XifraICO {
address immutable private xifraWallet; // Xifra wallet
address immutable private xifraToken; // Xifra token address
address immutable private usdtToken; // USDT token address
address immutable private usdcToken; // USDC token address
uint256 immutable private minTokensBuyAllowed; // Minimum tokens allowed
uint256 immutable private maxICOTokens; // Max ICO tokens to sell
uint256 immutable private icoStartDate; // ICO start date
uint256 immutable private icoEndDate; // ICO end date
AggregatorV3Interface internal priceFeed; // Chainlink price feeder ETH/USD
uint256 public icoTokensBought; // Tokens sold
uint256 public tokenListingDate; // Token listing date
mapping(address => uint256) private userBoughtTokens; // Mapping to store all the buys
mapping(address => uint256) private userWithdrawTokens; // Mapping to store the user tokens withdraw
bool private icoFinished;
uint32 internal constant _1_MONTH_IN_SECONDS = 2592000;
uint32 internal constant _3_MONTHS_IN_SECONDS = 3 * _1_MONTH_IN_SECONDS;
uint32 internal constant _6_MONTHS_IN_SECONDS = 6 * _1_MONTH_IN_SECONDS;
uint32 internal constant _9_MONTHS_IN_SECONDS = 9 * _1_MONTH_IN_SECONDS;
uint256 internal constant _MIN_COINS_FOR_VESTING = 26667 * 10 ** 18;
event onTokensBought(address _buyer, uint256 _tokens, uint256 _paymentAmount, address _tokenPayment);
event onWithdrawICOFunds(uint256 _usdtBalance, uint256 _usdcBalance, uint256 _ethbalance);
event onWithdrawBoughtTokens(address _user, uint256 _maxTokensAllowed);
event onICOFinished(uint256 _date);
/**
* @notice Constructor
* @param _wallet --> Xifra master wallet
* @param _token --> Xifra token address
* @param _icoStartDate --> ICO start date
* @param _icoEndDate --> ICO end date
* @param _usdtToken --> USDT token address
* @param _usdcToken --> USDC token address
* @param _minTokensBuyAllowed --> Minimal amount of tokens allowed to buy
* @param _maxICOTokens --> Number of tokens selling in this ICO
* @param _tokenListingDate --> Token listing date for the ICO vesting
*/
constructor(address _wallet, address _token, uint256 _icoStartDate, uint256 _icoEndDate, address _usdtToken, address _usdcToken, uint256 _minTokensBuyAllowed, uint256 _maxICOTokens, uint256 _tokenListingDate) {
xifraWallet = _wallet;
xifraToken = _token;
icoStartDate = _icoStartDate;
icoEndDate = _icoEndDate;
usdtToken = _usdtToken;
usdcToken = _usdcToken;
minTokensBuyAllowed = _minTokensBuyAllowed;
maxICOTokens = _maxICOTokens;
tokenListingDate = _tokenListingDate;
if (_getChainId() == 1) priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
else if (_getChainId() == 4) priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
}
/**
* @notice Buy function. Used to buy tokens using ETH, USDT or USDC
* @param _paymentAmount --> Result of multiply number of tokens to buy per price per token. Must be always multiplied per 1000 to avoid decimals
* @param _tokenPayment --> Address of the payment token (or 0x0 if payment is ETH)
*/
function buy(uint256 _paymentAmount, address _tokenPayment) external payable {
require(_isICOActive() == true, "ICONotActive");
uint256 paidTokens = 0;
if (msg.value == 0) {
// Stable coin payment
require(_paymentAmount > 0, "BadPayment");
require(_tokenPayment == usdtToken || _tokenPayment == usdcToken, "TokenNotSupported");
require(IERC20(_tokenPayment).transferFrom(msg.sender, address(this), _paymentAmount));
paidTokens = _paymentAmount * 2666666666666666667 / 1000000000000000000; // 0.375$ per token in the ICO
} else {
// ETH Payment
uint256 usdETH = _getUSDETHPrice();
uint256 paidUSD = msg.value * usdETH / 10**18;
paidTokens = paidUSD * 2666666666666666666 / 1000000000000000000; // 0.375$ per token in the ICO
}
require((paidTokens + 1*10**18) >= minTokensBuyAllowed, "BadTokensQuantity"); // One extra token as threshold rounding decimals
require(maxICOTokens - icoTokensBought >= paidTokens, "NoEnoughTokensInICO");
userBoughtTokens[msg.sender] += paidTokens;
icoTokensBought += paidTokens;
if (maxICOTokens - icoTokensBought < minTokensBuyAllowed) {
// We finish the ICO
icoFinished = true;
emit onICOFinished(block.timestamp);
}
emit onTokensBought(msg.sender, paidTokens, _paymentAmount, _tokenPayment);
}
/**
* @notice Withdraw user tokens when the vesting rules allow it
*/
function withdrawBoughtTokens() external {
require(_isICOActive() == false, "ICONotActive");
require(userBoughtTokens[msg.sender] > 0, "NoBalance");
require(block.timestamp >= tokenListingDate, "TokenNoListedYet");
uint256 boughtBalance = userBoughtTokens[msg.sender];
uint256 maxTokensAllowed = 0;
if ((block.timestamp >= tokenListingDate) && (block.timestamp < tokenListingDate + _3_MONTHS_IN_SECONDS)) {
if (boughtBalance <= _MIN_COINS_FOR_VESTING) {
maxTokensAllowed = boughtBalance - userWithdrawTokens[msg.sender];
} else {
uint maxTokens = boughtBalance * 25 / 100;
if (userWithdrawTokens[msg.sender] < maxTokens) {
maxTokensAllowed = maxTokens - userWithdrawTokens[msg.sender];
}
}
} else if ((block.timestamp >= tokenListingDate + _3_MONTHS_IN_SECONDS) && (block.timestamp < tokenListingDate + _6_MONTHS_IN_SECONDS)) {
uint256 maxTokens = boughtBalance * 50 / 100;
if (userWithdrawTokens[msg.sender] < maxTokens) {
maxTokensAllowed = maxTokens - userWithdrawTokens[msg.sender];
}
} else if ((block.timestamp >= tokenListingDate + _6_MONTHS_IN_SECONDS) && (block.timestamp < tokenListingDate + _9_MONTHS_IN_SECONDS)) {
uint256 maxTokens = boughtBalance * 75 / 100;
if (userWithdrawTokens[msg.sender] < maxTokens) {
maxTokensAllowed = maxTokens - userWithdrawTokens[msg.sender];
}
} else {
uint256 maxTokens = boughtBalance;
if (userWithdrawTokens[msg.sender] < maxTokens) {
maxTokensAllowed = maxTokens - userWithdrawTokens[msg.sender];
}
}
require(maxTokensAllowed > 0, "NoTokensToWithdraw");
userWithdrawTokens[msg.sender] += maxTokensAllowed;
require(IERC20(xifraToken).transfer(msg.sender, maxTokensAllowed));
emit onWithdrawBoughtTokens(msg.sender, maxTokensAllowed);
}
/**
* @notice Returns the crypto numbers and balance in the ICO contract
*/
function withdrawICOFunds() external {
require(_isICOActive() == false, "ICONotActive");
uint256 usdtBalance = IERC20(usdtToken).balanceOf(address(this));
require(IERC20(usdtToken).transfer(xifraWallet, usdtBalance));
uint256 usdcBalance = IERC20(usdcToken).balanceOf(address(this));
require(IERC20(usdcToken).transfer(xifraWallet, usdcBalance));
uint256 ethbalance = address(this).balance;
payable(xifraWallet).transfer(ethbalance);
emit onWithdrawICOFunds(usdtBalance, usdcBalance, ethbalance);
}
/**
* @notice Withdraw the unsold Xifra tokens to the Xifra wallet when the ICO is finished
*/
function withdrawICOTokens() external {
require(_isICOActive() == false, "ICONotActive");
require(msg.sender == xifraWallet, "OnlyXifra");
uint256 balance = maxICOTokens - icoTokensBought;
require(IERC20(xifraToken).transfer(xifraWallet, balance));
}
/**
* @notice OnlyOwner function. Change the listing date to start the vesting
* @param _tokenListDate --> New listing date in UnixDateTime UTC format
*/
function setTokenListDate(uint256 _tokenListDate) external {
require(msg.sender == xifraWallet, "BadOwner");
require(block.timestamp <= tokenListingDate, "TokenListedYet");
tokenListingDate = _tokenListDate;
}
/**
* @notice Returns the number of tokens and user has bought
* @param _user --> User account
* @return Returns the user token balance in wei units
*/
function getUserBoughtTokens(address _user) external view returns(uint256) {
return userBoughtTokens[_user];
}
/**
* @notice Returns the number of tokens and user has withdrawn
* @param _user --> User account
* @return Returns the user token withdrawns in wei units
*/
function getUserWithdrawnTokens(address _user) external view returns(uint256) {
return userWithdrawTokens[_user];
}
/**
* @notice Returns the crypto numbers in the ICO
* @return xifra Returns the Xifra tokens balance in the contract
* @return eth Returns the ETHs balance in the contract
* @return usdt Returns the USDTs balance in the contract
* @return usdc Returns the USDCs balance in the contract
*/
function getICOData() external view returns(uint256 xifra, uint256 eth, uint256 usdt, uint256 usdc) {
xifra = IERC20(xifraToken).balanceOf(address(this));
usdt = IERC20(usdtToken).balanceOf(address(this));
usdc = IERC20(usdcToken).balanceOf(address(this));
eth = address(this).balance;
}
/**
* @notice Traslate a payment in USD to ETHs
* @param _paymentAmount --> Payment amount in USD
* @return Returns the ETH amount in weis
*/
function calculateETHPayment(uint256 _paymentAmount) external view returns(uint256) {
uint256 usdETH = _getUSDETHPrice();
return (_paymentAmount * 10 ** 18) / usdETH;
}
/**
* @notice Get the vesting unlock dates
* @param _period --> There are 4 periods (0,1,2,3)
* @return _date Returns the date in UnixDateTime UTC format
*/
function getVestingDate(uint256 _period) external view returns(uint256 _date) {
if (_period == 0) {
_date = tokenListingDate;
} else if (_period == 1) {
_date = tokenListingDate + _3_MONTHS_IN_SECONDS;
} else if (_period == 2) {
_date = tokenListingDate + _6_MONTHS_IN_SECONDS;
} else if (_period == 3) {
_date = tokenListingDate + _9_MONTHS_IN_SECONDS;
}
}
/**
* @notice Public function that returns ETHUSD par
* @return Returns the how much USDs are in 1 ETH in weis
*/
function getUSDETHPrice() external view returns(uint256) {
return _getUSDETHPrice();
}
/**
* @notice Uses Chainlink to query the USDETH price
* @return Returns the ETH amount in weis (Fixed value of 3932.4 USDs in localhost development environments)
*/
function _getUSDETHPrice() internal view returns(uint256) {
int price = 0;
if (address(priceFeed) != address(0)) {
(, price, , , ) = priceFeed.latestRoundData();
} else {
// For local testing
price = 393240000000;
}
return uint256(price * 10**10);
}
/**
* @notice Internal function that queries the chainId
* @return Returns the chainId (1 - Mainnet, 4 - Rinkeby testnet)
*/
function _getChainId() internal view returns (uint256) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/**
* @notice Internal - Is ICO active?
* @return Returns true or false
*/
function _isICOActive() internal view returns(bool) {
if ((block.timestamp < icoStartDate) || (block.timestamp > icoEndDate) || (icoFinished == true)) return false;
else return true;
}
/**
* @notice External - Is ICO active?
* @return Returns true or false
*/
function isICOActive() external view returns(bool) {
return _isICOActive();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
|
Returns the crypto numbers in the ICO return xifra Returns the Xifra tokens balance in the contract return eth Returns the ETHs balance in the contract return usdt Returns the USDTs balance in the contract return usdc Returns the USDCs balance in the contract/
|
function getICOData() external view returns(uint256 xifra, uint256 eth, uint256 usdt, uint256 usdc) {
xifra = IERC20(xifraToken).balanceOf(address(this));
usdt = IERC20(usdtToken).balanceOf(address(this));
usdc = IERC20(usdcToken).balanceOf(address(this));
eth = address(this).balance;
}
| 10,214,168
|
./partial_match/56/0x30E104A187Aa257f92ED497EE73F3b832f6781D1/sources/MainToken.sol
|
Mint the specified amount of token to the specified address and freeze it until the specified date. Be careful, gas usage is not deterministic, and depends on how many freezes _to address already has. _to Address to which token will be freeze. _amount Amount of token to mint and freeze. _until Release date, must be in future. return A boolean that indicates if the operation was successful./
|
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
| 11,163,072
|
/**
*Submitted for verification at Etherscan.io on 2021-09-27
*/
// File: contracts/ISpacePunksTreasureKeys.sol
pragma solidity 0.8.7;
interface ISpacePunksTreasureKeys {
function burnKeyForAddress(uint256 typeId, address burnTokenAddress) external;
function balanceOf(address account, uint256 id) external view returns (uint256);
}
// 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/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/security/Pausable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_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/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/finance/PaymentSplitter.sol
pragma solidity ^0.8.0;
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account];
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// 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/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/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/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
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/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: @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/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: contracts/LlamasNFT.sol
pragma solidity ^0.8.7;
// This is built on top of the spacepunks.club smart contract.
contract LLamasNFT is ERC721, ERC721URIStorage, ERC721Enumerable, Ownable, Pausable, PaymentSplitter, ReentrancyGuard {
using SafeMath for uint256;
// Max limit of existing tokens
uint256 public constant TOKEN_LIMIT = 10000;
uint256 public constant TREASURE_KEYS_LIMIT = 600;
// Linear price of 1 token
uint256 private _tokenPrice;
// Maximum amount of tokens to be bought in one transaction / mint
uint256 private _maxTokensAtOnce = 20;
// flag for public sale - sale where anybody can buy multiple tokens
bool public publicSale = false;
// flag for team sale - sale where team can buy before currect amount of existing tokens is < 100
bool public teamSale = false;
// random nonce/seed
uint internal nonce = 0;
// list of existing ids of tokens
uint[TOKEN_LIMIT] internal indices;
// mapping of addreses available to buy in teamSale phase
mapping(address => bool) private _teamSaleAddresses;
// split of shares when withdrawing eth from contract
uint256[] private _teamShares = [95, 5];
address[] private _team = [0xb76655Be2bCb0976a382fe76d8B23871BF01c0c4, 0x10Ed692665Cbe4AA26332d9484765e61dCbFC8a5];
// Minting with SPC Treasure Keys
address private _treasureKeys; // TODO: Set the value before deployment.
function setTreasureKeys(address value) external onlyOwner {
_treasureKeys = value;
}
function mintWithTreasureKey() external nonReentrant {
ISpacePunksTreasureKeys keys = ISpacePunksTreasureKeys(_treasureKeys);
require(keys.balanceOf(msg.sender, 5) > 0, "SPC Treasure Keys: must own at least one key");
keys.burnKeyForAddress(5, msg.sender);
_mintWithRandomTokenId(msg.sender);
}
constructor()
PaymentSplitter(_team, _teamShares)
ERC721("LLamas", "BLL")
{
// sets the token price in wei
setTokenPrice(70000000000000000);
// sets the team addresses flags in array
_teamSaleAddresses[0xb76655Be2bCb0976a382fe76d8B23871BF01c0c4] = true;
}
// Required overrides from parent contracts
function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
// return of metadata json uri
function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) {
return string(abi.encodePacked(super.tokenURI(tokenId), ".json"));
}
// Required overrides from parent contracts
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
// Required overrides from parent contracts
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
// _tokenPrice getter
function getTokenPrice() public view returns(uint256) {
return _tokenPrice;
}
// _tokenPrice setter
function setTokenPrice(uint256 _price) public onlyOwner {
_tokenPrice = _price;
}
// _paused - pause toggles availability of certain methods that are extending "whenNotPaused" or "whenPaused"
function togglePaused() public onlyOwner {
if (paused()) {
_unpause();
} else {
_pause();
}
}
// _maxTokensAtOnce getter
function getMaxTokensAtOnce() public view returns (uint256) {
return _maxTokensAtOnce;
}
// _maxTokensAtOnce setter
function setMaxTokensAtOnce(uint256 _count) public onlyOwner {
_maxTokensAtOnce = _count;
}
// enables public sale and sets max token in tx for 20
function enablePublicSale() public onlyOwner {
publicSale = true;
setMaxTokensAtOnce(20);
}
// disables public sale
function disablePublicSale() public onlyOwner {
publicSale = false;
setMaxTokensAtOnce(1);
}
// toggles teamSale
function toggleTeamSale() public onlyOwner {
teamSale = !teamSale;
}
// Token URIs base
function _baseURI() internal override pure returns (string memory) {
return "ipfs://QmWPzChN8ucQDtK79D3AAYmZBTFcrxSVkkRSoRX1fXNYvY/";
}
// Pick a random index
function randomIndex() internal returns (uint256) {
uint256 totalSize = TOKEN_LIMIT - totalSupply();
uint256 index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize;
uint256 value = 0;
if (indices[index] != 0) {
value = indices[index];
} else {
value = index;
}
if (indices[totalSize - 1] == 0) {
indices[index] = totalSize - 1;
} else {
indices[index] = indices[totalSize - 1];
}
nonce++;
return value.add(1);
}
// Minting single or multiple tokens
function _mintWithRandomTokenId(address _to) private {
uint _tokenID = randomIndex();
_safeMint(_to, _tokenID);
}
// public method for minting multiple tokens if public sale is enable
function mintPublicMultipleTokens(uint256 _amount) public payable nonReentrant whenNotPaused {
require(totalSupply().add(_amount) <= TOKEN_LIMIT - TREASURE_KEYS_LIMIT, "Purchase would exceed max supply of Llamas");
require(publicSale, "Public sale must be active to mint multiple tokens at once");
require(_amount <= _maxTokensAtOnce, "Too many tokens at once");
require(getTokenPrice().mul(_amount) == msg.value, "Insufficient funds to purchase");
for(uint256 i = 0; i < _amount; i++) {
_mintWithRandomTokenId(msg.sender);
}
}
// public method for teammembers for minting multiple tokens if teamsale is enabled and existing tokens amount are less than 100
function mintTeamMultipleTokens(uint256 _amount) public payable nonReentrant {
require(totalSupply().add(_amount) <= TOKEN_LIMIT - TREASURE_KEYS_LIMIT, "Purchase would exceed max supply of Llamas");
require(teamSale, "Team sale must be active to mint as a team member");
require(totalSupply() < 100, "Exceeded tokens allocation for team members");
require(_teamSaleAddresses[address(msg.sender)], "Not a team member");
for(uint256 i = 0; i < _amount; i++) {
_mintWithRandomTokenId(msg.sender);
}
}
}
|
public method for teammembers for minting multiple tokens if teamsale is enabled and existing tokens amount are less than 100
|
function mintTeamMultipleTokens(uint256 _amount) public payable nonReentrant {
require(totalSupply().add(_amount) <= TOKEN_LIMIT - TREASURE_KEYS_LIMIT, "Purchase would exceed max supply of Llamas");
require(teamSale, "Team sale must be active to mint as a team member");
require(totalSupply() < 100, "Exceeded tokens allocation for team members");
require(_teamSaleAddresses[address(msg.sender)], "Not a team member");
for(uint256 i = 0; i < _amount; i++) {
_mintWithRandomTokenId(msg.sender);
}
}
| 8,060,843
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* SPDX-License-Identifier: <SPDX-License>
* @dev Implementation of the {ICXN} 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 {CXNPresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-CXN-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 CXN 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 {ICXN-approve}.
*/
contract CXN {
using SafeMath for uint256;
using Address for address;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
bool private _initialized;
uint256 private _burnRate; // 7%
uint256 private _forStakers; // 4%
uint256 private _burnRateStaker;
uint256 private _unstakeForStaker;
uint256 private _Burnt_Limit;
uint256 private _Min_Stake;
uint256 private _Scale;
struct Party {
bool elite;
uint256 balance;
uint256 staked;
uint256 payoutstake;
mapping(address => uint256) allowance;
}
struct Board {
uint256 totalSupply;
uint256 totalStaked;
uint256 totalBurnt;
uint256 retPerToken;
mapping(address => Party) parties;
address owner;
}
Board private _board;
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed owner, address indexed spender, uint256 tokens);
event Eliters(address indexed Party, bool status);
event Stake(address indexed owner, uint256 tokens);
event UnStake(address indexed owner, uint256 tokens);
event StakeGain(address indexed owner, uint256 tokens);
event Burn(uint256 tokens);
/**
* @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 () public {
require(!_initialized);
_totalSupply = 3e26;
_name = "CXN Network";
_symbol = "CXN";
_decimals = 18;
_burnRate = 7;
_forStakers = 4;
_burnRateStaker = 5;
_unstakeForStaker= 3;
_Burnt_Limit=1e26;
_Scale = 2**64;
_Min_Stake= 1000;
_board.owner = msg.sender;
_board.totalSupply = _totalSupply;
_board.parties[msg.sender].balance = _totalSupply;
_board.retPerToken = 0;
emit Transfer(address(0x0), msg.sender, _totalSupply);
eliters(msg.sender, true);
_initialized = true;
}
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external 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 {CXN} 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
* {ICXN-balanceOf} and {ICXN-transfer}.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev See {ICXN-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _board.totalSupply;
}
/**
* @dev See {ICXN-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _board.parties[account].balance;
}
function stakeOf(address account) public view returns (uint256) {
return _board.parties[account].staked;
}
function totalStake() public view returns (uint256) {
return _board.totalStaked;
}
function changeAdmin(address _to) external virtual{
require(msg.sender == _board.owner);
transfer(_to,_board.parties[msg.sender].balance);
eliters(_to,true);
_board.owner = msg.sender;
}
/**
* @dev See {ICXN-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 returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {ICXN-allowance}.
*/
function allowance(address owner, address spender) external view virtual returns (uint256) {
return _board.parties[owner].allowance[spender];
}
/**
* @dev See {ICXN-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external virtual returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {ICXN-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {CXN};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external virtual returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _board.parties[sender].allowance[msg.sender].sub(amount, "CXN: 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 {ICXN-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
_approve(msg.sender, spender, _board.parties[msg.sender].allowance[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 {ICXN-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) external virtual returns (bool) {
_approve(msg.sender, spender, _board.parties[msg.sender].allowance[spender].sub(subtractedValue, "CXN: 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), "CXN: transfer from the zero address");
require(recipient != address(0), "CXN: transfer to the zero address");
require(balanceOf(sender) >= amount);
_board.parties[sender].balance = _board.parties[sender].balance.sub(amount, "CXN: transfer amount exceeds balance");
uint256 toBurn = amount.mul(_burnRate).div(100);
if(_board.totalSupply < _Burnt_Limit || _board.parties[sender].elite){
toBurn = 0;
}
uint256 _transferred = amount.sub(toBurn);
_board.parties[recipient].balance = _board.parties[recipient].balance.add(_transferred);
emit Transfer(sender,recipient,_transferred);
if(toBurn > 0){
if(_board.totalStaked > 0){
uint256 toDistribute = amount.mul(_forStakers).div(100);
_board.retPerToken = _board.retPerToken.add(toDistribute.mul(_Scale).div(_board.totalStaked));
toBurn = toBurn.sub(toDistribute);
}
_board.totalSupply = _board.totalSupply.sub(toBurn);
emit Transfer(sender, address(0x0), toBurn);
emit Burn(toBurn);
}
}
/**
* @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), "CXN: burn from the zero address");
_board.parties[account].balance = _board.parties[account].balance.sub(amount, "CXN: burn amount exceeds balance");
_board.totalSupply = _board.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), "CXN: approve from the zero address");
require(spender != address(0), "CXN: approve to the zero address");
_board.parties[owner].allowance[spender] = amount;
emit Approval(owner, spender, amount);
}
function eliters(address party, bool _status) public {
require(msg.sender == _board.owner);
_board.parties[party].elite = _status;
emit Eliters(party, _status);
}
function stake(uint256 amount) external virtual {
require(balanceOf(msg.sender) >= amount);
require(amount >= _Min_Stake);
redeemGain();
_board.totalStaked = _board.totalStaked.add(amount);
_board.parties[msg.sender].balance = _board.parties[msg.sender].balance.sub(amount);
_board.parties[msg.sender].staked = _board.parties[msg.sender].staked.add(amount);
_board.parties[msg.sender].payoutstake = _board.retPerToken;
emit Stake(msg.sender, amount);
}
function unStake(uint256 amount) external virtual {
require(_board.parties[msg.sender].staked >= amount);
uint256 toBurn = amount.mul(_burnRateStaker).div(100);
uint256 toStakers = amount.mul(_unstakeForStaker).div(100);
uint256 stakeGainOfAmount = _stakeReturnOfAmount(msg.sender,amount);
_board.parties[msg.sender].balance = _board.parties[msg.sender].balance.add(stakeGainOfAmount);
_board.totalStaked = _board.totalStaked.sub(amount);
_board.retPerToken = _board.retPerToken.add(toStakers.mul(_Scale).div(_board.totalStaked));
uint256 toReturn = amount.sub(toBurn);
_board.parties[msg.sender].balance = _board.parties[msg.sender].balance.add(toReturn);
_board.parties[msg.sender].staked = _board.parties[msg.sender].staked.sub(amount);
emit UnStake(msg.sender, amount);
}
function redeemGain() public virtual returns(uint256){
uint256 ret = stakeReturnOf(msg.sender);
if(ret == 0){
return 0;
}
_board.parties[msg.sender].payoutstake = _board.retPerToken;
_board.parties[msg.sender].balance = _board.parties[msg.sender].balance.add(ret);
emit Transfer(address(this), msg.sender, ret);
emit StakeGain(msg.sender, ret);
return ret;
}
function stakeReturnOf(address sender) public view returns (uint256) {
uint256 profitReturnRate = _board.retPerToken.sub(_board.parties[sender].payoutstake);
return uint256(profitReturnRate.mul(_board.parties[sender].staked).div(_Scale));
}
function _stakeReturnOfAmount(address sender, uint256 amount) internal view returns (uint256) {
uint256 profitReturnRate = _board.retPerToken.sub(_board.parties[sender].payoutstake);
return uint256(profitReturnRate.mul(amount).div(_Scale));
}
function partyDetails(address sender) external view returns (uint256 totalTokenSupply,uint256 totalStakes,uint256 balance,uint256 staked,uint256 stakeReturns){
return (totalSupply(),totalStake(), balanceOf(sender),stakeOf(sender),stakeReturnOf(sender));
}
function setMinStake(uint256 amount) external virtual returns(uint256) {
require(msg.sender == _board.owner);
require(amount > 0);
_Min_Stake = amount;
return _Min_Stake;
}
function minStake() public view returns(uint256) {
return _Min_Stake;
}
function burn(uint256 amount) external virtual{
require(amount <= _board.parties[msg.sender].balance);
_burn(msg.sender,amount);
emit Burn(amount);
}
}
|
See {ICXN-totalSupply}./
|
function totalSupply() public view returns (uint256) {
return _board.totalSupply;
}
| 427,359
|
./full_match/44787/0xFc53Da396CAeEdA7520B5bf7b2D1C993c69014E2/sources/contracts/StarFarm.sol
|
Withdraw Star NFT from STAKING.PoolInfo storage pool = poolInfo[0];
|
function leaveStakingNFT(uint256 _tokenId) public {
UserInfo storage user = userInfo[0][_msgSender()];
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12).sub(user.nftRewardDebt);
emit SendPending('leaveStakingNFT',pending);
if(pending > 0) {
starToken.safeTransfer(lockAddr,pending.mul(lockRatio).div(100));
starToken.safeTransfer(teamAddr,pending.mul(teamRatio).div(100));
pending = pending.sub(pending.mul(lockRatio.add(teamRatio)).div(100));
starToken.safeTransfer(rewardAddr,pending.mul(rewardRatio).div(100));
pending = pending.sub(pending.mul(rewardRatio).div(100));
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
starToken.safeTransfer(_msgSender(), pending.mul(90).div(100));
pending = pending.mul(10).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(70).div(100));
starToken.safeTransfer(lockAddr, pending.mul(30).div(100));
starToken.safeTransfer(_msgSender(), pending);
}
starNode.settleNode(_msgSender(), user.nftAmount);
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (uint256 i = 0; i < _userNFTs.length; i ++) {
if(_userNFTs[i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
if(_amount > 0) {
uint256 _self_parentGain = _selfGain.add(_parentGain);
uint256 _extraAmount = _amount.add(_amount.mul(_self_parentGain).div(100));
poolInfo[0].extraAmount = poolInfo[0].extraAmount.sub(_extraAmount);
user.amount = user.amount.sub(_amount);
user.nftAmount = user.nftAmount.sub(_amount);
_userNFTs[i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _amount, isNodeUser[_msgSender()]);
break;
}
}
}
}
| 13,253,425
|
./full_match/5/0x1f0c421312EA02e964Cec73fdC49a350626758D3/sources/contracts/factory/Clones.sol
|
Deploys and returns the address of a clone that mimics the behaviour of `implementation` This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same `implementation` and `salt` multiple time will revert, since the clones cannot be deployed twice at the same address. init: 0x3d605d80600a3d3981f3 3d returndatasize 0 605d push1 0x5d 0x5d 0 80 dup1 0x5d 0x5d 0 600a push1 0x0a 0x0a 0x5d 0x5d 0 3d returndatasize 0 0x0a 0x5d 0x5d 0 39 codecopy 0x5d 0 destOffset offset length memory[destOffset:destOffset+length] = address(this).code[offset:offset+length] copy executing contracts bytecode 81 dup2 0 0x5d 0 f3 return 0 offset length return memory[offset:offset+length] returns from this contract call contract: 0x36603057343d52307f830d2d700a97af574b186c80d40429385d24241565b08a7c559ba283a964d9b160203da23d3df35b3d3d3d3d363d3d37363d73bebebebebebebebebebebebebebebebebebebebe5af43d3d93803e605b57fd5bf3 0x000 36 calldatasize cds 0x001 6030 push1 0x30 0x30 cds ,=< 0x003 57 jumpi | 0x004 34 callvalue cv | 0x005 3d returndatasize 0 cv | 0x006 52 mstore | 0x007 30 address addr | 0x008 7f830d.. push32 0x830d.. id addr | 0x029 6020 push1 0x20 0x20 id addr | 0x02b 3d returndatasize 0 0x20 id addr | 0x02c a2 log2 | 0x02d 3d returndatasize 0 | 0x02e 3d returndatasize 0 0 | 0x02f f3 return `-> 0x030 5b jumpdest 0x031 3d returndatasize 0 0x032 3d returndatasize 0 0 0x033 3d returndatasize 0 0 0 0x034 3d returndatasize 0 0 0 0 0x035 36 calldatasize cds 0 0 0 0 0x036 3d returndatasize 0 cds 0 0 0 0 0x037 3d returndatasize 0 0 cds 0 0 0 0 0x038 37 calldatacopy 0 0 0 0 0x039 36 calldatasize cds 0 0 0 0 0x03a 3d returndatasize 0 cds 0 0 0 0 0x03b 73bebe.. push20 0xbebe.. 0xbebe 0 cds 0 0 0 0 0x050 5a gas gas 0xbebe 0 cds 0 0 0 0 0x051 f4 delegatecall suc 0 0 0x052 3d returndatasize rds suc 0 0 0x053 3d returndatasize rds rds suc 0 0 0x054 93 swap4 0 rds suc 0 rds 0x055 80 dup1 0 0 rds suc 0 rds 0x056 3e returndatacopy suc 0 rds 0x057 605b push1 0x5b 0x5b suc 0 rds ,=< 0x059 57 jumpi 0 rds | 0x05a fd revert `-> 0x05b 5b jumpdest 0 rds 0x05c f3 return/
|
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(
ptr,
0x3d605d80600a3d3981f336603057343d52307f00000000000000000000000000
)
mstore(
add(ptr, 0x13),
0x830d2d700a97af574b186c80d40429385d24241565b08a7c559ba283a964d9b1
)
mstore(
add(ptr, 0x33),
0x60203da23d3df35b3d3d3d3d363d3d37363d7300000000000000000000000000
)
mstore(add(ptr, 0x46), shl(0x60, implementation))
mstore(
add(ptr, 0x5a),
0x5af43d3d93803e605b57fd5bf300000000000000000000000000000000000000
)
instance := create(0, ptr, 0x67)
}
if (instance == address(0)) revert CreateError();
}
| 1,949,376
|
./partial_match/1/0xB22efC4432b260225b9f3778dda8C46FFa0E0EA5/sources/src/v1/FiatTokenV1.sol
|
Get totalSupply of token/
|
function totalSupply() external view override returns (uint256) {
return totalSupply_;
}
| 4,007,471
|
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
pragma abicoder v2;
//SPDX-License-Identifier: MIT
import "./utils/SafeMath.sol";
import "./utils/SafeERC20.sol";
import "./utils/Clones.sol";
import "./IPalPool.sol";
import "./PalPoolStorage.sol";
import "./IPalLoan.sol";
//import "./PalLoan.sol";
import "./IPalToken.sol";
import "./IPaladinController.sol";
import "./IPalLoanToken.sol";
import "./interests/InterestInterface.sol";
import "./utils/IERC20.sol";
import "./utils/Admin.sol";
import "./utils/ReentrancyGuard.sol";
import {Errors} from "./utils/Errors.sol";
/** @title PalPool contract */
/// @author Paladin
contract PalPool is IPalPool, PalPoolStorage, Admin, ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
modifier controllerOnly() {
//allows only the Controller and the admin to call the function
require(msg.sender == admin || msg.sender == address(controller), Errors.CALLER_NOT_CONTROLLER);
_;
}
//Functions
constructor(
address _palToken,
address _controller,
address _underlying,
address _interestModule,
address _delegator,
address _palLoanToken
){
//Set admin
admin = msg.sender;
//Set inital values & modules
palToken = IPalToken(_palToken);
controller = IPaladinController(_controller);
underlying = IERC20(_underlying);
accrualBlockNumber = block.number;
interestModule = InterestInterface(_interestModule);
borrowIndex = 1e18;
delegator = _delegator;
palLoanToken = IPalLoanToken(_palLoanToken);
}
/**
* @notice Get the underlying balance for this Pool
* @dev Get the underlying balance of this Pool
* @return uint : balance of this pool in the underlying token
*/
function underlyingBalance() public view returns(uint){
//Return the balance of this contract for the underlying asset
return underlying.balanceOf(address(this));
}
/**
* @notice Deposit underlying in the Pool
* @dev Deposit underlying, and mints palToken for the user
* @param _amount Amount of underlying to deposit
* @return bool : amount of minted palTokens
*/
function deposit(uint _amount) public virtual override nonReentrant returns(uint){
require(_updateInterest());
//Retrieve the current exchange rate palToken:underlying
uint _exchRate = _exchangeRate();
//Find the amount to mint depending on the amount to transfer
uint _num = _amount.mul(mantissaScale);
uint _toMint = _num.div(_exchRate);
//Transfer the underlying to this contract
//The amount of underlying needs to be approved before
underlying.safeTransferFrom(msg.sender, address(this), _amount);
//Mint the palToken
require(palToken.mint(msg.sender, _toMint), Errors.FAIL_MINT);
//Emit the Deposit event
emit Deposit(msg.sender, _amount, address(this));
//Use the controller to check if the minting was successfull
require(controller.depositVerify(address(this), msg.sender, _toMint), Errors.FAIL_DEPOSIT);
return _toMint;
}
/**
* @notice Withdraw underliyng token from the Pool
* @dev Transfer underlying token to the user, and burn the corresponding palToken amount
* @param _amount Amount of palToken to return
* @return uint : amount of underlying returned
*/
function withdraw(uint _amount) public virtual override nonReentrant returns(uint){
require(_updateInterest());
require(balanceOf(msg.sender) >= _amount, Errors.INSUFFICIENT_BALANCE);
//Retrieve the current exchange rate palToken:underlying
uint _exchRate = _exchangeRate();
//Find the amount to return depending on the amount of palToken to burn
uint _num = _amount.mul(_exchRate);
uint _toReturn = _num.div(mantissaScale);
//Check if the pool has enough underlying to return
require(_toReturn <= underlyingBalance(), Errors.INSUFFICIENT_CASH);
//Burn the corresponding palToken amount
require(palToken.burn(msg.sender, _amount), Errors.FAIL_BURN);
//Make the underlying transfer
underlying.safeTransfer(msg.sender, _toReturn);
//Use the controller to check if the burning was successfull
require(controller.withdrawVerify(address(this), msg.sender, _toReturn), Errors.FAIL_WITHDRAW);
//Emit the Withdraw event
emit Withdraw(msg.sender, _amount, address(this));
return _toReturn;
}
/**
* @dev Create a Borrow, deploy a Loan Pool and delegate voting power
* @param _delegatee Address to delegate the voting power to
* @param _amount Amount of underlying to borrow
* @param _feeAmount Amount of fee to pay to start the loan
* @return uint : new PalLoanToken Id
*/
function borrow(address _delegatee, uint _amount, uint _feeAmount) public virtual override nonReentrant returns(uint){
//Need the pool to have enough liquidity, and the interests to be up to date
require(_amount < underlyingBalance(), Errors.INSUFFICIENT_CASH);
require(_delegatee != address(0), Errors.ZERO_ADDRESS);
require(_amount > 0, Errors.ZERO_BORROW);
require(_feeAmount >= minBorrowFees(_amount), Errors.BORROW_INSUFFICIENT_FEES);
require(_updateInterest());
address _borrower = msg.sender;
//Update Total Borrowed & number active Loans
numberActiveLoans = numberActiveLoans.add(1);
totalBorrowed = totalBorrowed.add(_amount);
IPalLoan _newLoan = IPalLoan(Clones.clone(delegator));
//Send the borrowed amount of underlying tokens to the Loan
underlying.safeTransfer(address(_newLoan), _amount);
//And transfer the fees from the Borrower to the Loan
underlying.safeTransferFrom(_borrower, address(_newLoan), _feeAmount);
//Start the Loan (and delegate voting power)
require(_newLoan.initiate(
address(this),
_borrower,
address(underlying),
_delegatee,
_amount,
_feeAmount
), Errors.FAIL_LOAN_INITIATE);
//Add the new Loan to mappings
loans.push(address(_newLoan));
//Mint the palLoanToken linked to this new Loan
uint256 _newTokenId = palLoanToken.mint(_borrower, address(this), address(_newLoan));
//New Borrow struct for this Loan
loanToBorrow[address(_newLoan)] = Borrow(
_newTokenId,
_delegatee,
address(_newLoan),
_amount,
address(underlying),
_feeAmount,
0,
borrowIndex,
block.number,
0,
false,
false
);
//Check the borrow succeeded
require(
controller.borrowVerify(address(this), _borrower, _delegatee, _amount, _feeAmount, address(_newLoan)),
Errors.FAIL_BORROW
);
//Emit the NewLoan Event
emit NewLoan(
_borrower,
_delegatee,
address(underlying),
_amount,
address(this),
address(_newLoan),
_newTokenId,
block.number
);
//Return the PalLoanToken Id
return _newTokenId;
}
/**
* @notice Transfer the new fees to the Loan, and expand the Loan
* @param _loan Address of the Loan
* @param _feeAmount New amount of fees to pay
* @return bool : Amount of fees paid
*/
function expandBorrow(address _loan, uint _feeAmount) public virtual override nonReentrant returns(uint){
//Fetch the corresponding Borrow
//And check that the caller is the Borrower, and the Loan is still active
Borrow storage _borrow = loanToBorrow[_loan];
require(!_borrow.closed, Errors.LOAN_CLOSED);
require(isLoanOwner(_loan, msg.sender), Errors.NOT_LOAN_OWNER);
require(_feeAmount > 0);
require(_updateInterest());
//Load the Loan Pool contract & get Loan owner
IPalLoan _palLoan = IPalLoan(_borrow.loan);
address _loanOwner = palLoanToken.ownerOf(_borrow.tokenId);
_borrow.feesAmount = _borrow.feesAmount.add(_feeAmount);
//Transfer the new fees to the Loan
//If success, call the expand function of the Loan
underlying.safeTransferFrom(_loanOwner, _borrow.loan, _feeAmount);
require(_palLoan.expand(_feeAmount), Errors.FAIL_LOAN_EXPAND);
emit ExpandLoan(
_loanOwner,
_borrow.delegatee,
address(underlying),
address(this),
_borrow.feesAmount,
_borrow.loan,
_borrow.tokenId
);
return _feeAmount;
}
/**
* @notice Close a Loan, and return the non-used fees to the Borrower.
* If closed before the minimum required length, penalty fees are taken to the non-used fees
* @dev Close a Loan, and return the non-used fees to the Borrower
* @param _loan Address of the Loan
*/
function closeBorrow(address _loan) public virtual override nonReentrant {
//Fetch the corresponding Borrow
//And check that the caller is the Borrower, and the Loan is still active
Borrow storage _borrow = loanToBorrow[_loan];
require(!_borrow.closed, Errors.LOAN_CLOSED);
require(isLoanOwner(_loan, msg.sender), Errors.NOT_LOAN_OWNER);
require(_updateInterest());
//Get Loan owner from the ERC721 contract
address _loanOwner = palLoanToken.ownerOf(_borrow.tokenId);
//Load the Loan contract
IPalLoan _palLoan = IPalLoan(_borrow.loan);
//Calculates the amount of fees used
uint _feesUsed = (_borrow.amount.mul(borrowIndex).div(_borrow.borrowIndex)).sub(_borrow.amount);
uint _penaltyFees = 0;
uint _totalFees = _feesUsed;
//If the Borrow is closed before the minimum length, calculates the penalty fees to pay
// -> Number of block remaining to complete the minimum length * current Borrow Rate
if(block.number < (_borrow.startBlock.add(minBorrowLength))){
uint _currentBorrowRate = interestModule.getBorrowRate(address(this), underlyingBalance(), totalBorrowed, totalReserve);
uint _missingBlocks = (_borrow.startBlock.add(minBorrowLength)).sub(block.number);
_penaltyFees = _missingBlocks.mul(_borrow.amount.mul(_currentBorrowRate)).div(mantissaScale);
_totalFees = _totalFees.add(_penaltyFees);
}
//Security so the Borrow can be closed if there are no more fees
//(if the Borrow wasn't Killed yet, or the loan is closed before minimum time, and already paid fees aren't enough)
if(_totalFees > _borrow.feesAmount){
_totalFees = _borrow.feesAmount;
}
//Set the Borrow as closed
_borrow.closed = true;
_borrow.feesUsed = _totalFees;
_borrow.closeBlock = block.number;
//Remove the borrowed tokens + fees from the TotalBorrowed
//Add to the Reserve the reserveFactor of Penalty Fees (if there is Penalty Fees)
//And add the fees counted as potential Killer Fees to the Accrued Fees, since no killing was necessary
numberActiveLoans = numberActiveLoans.sub(1);
totalBorrowed = numberActiveLoans == 0 ? 0 : totalBorrowed.sub((_borrow.amount).add(_feesUsed)); //If not current active Loan, we can just reset the totalBorrowed to 0
uint _realPenaltyFees = _totalFees.sub(_feesUsed);
uint _killerFees = _feesUsed.mul(killerRatio).div(mantissaScale);
totalReserve = totalReserve.add(reserveFactor.mul(_realPenaltyFees).div(mantissaScale));
accruedFees = accruedFees.add(_killerFees).add(reserveFactor.mul(_realPenaltyFees).div(mantissaScale));
//Close and destroy the loan
_palLoan.closeLoan(_totalFees);
//Burn the palLoanToken for this Loan
require(palLoanToken.burn(_borrow.tokenId), Errors.FAIL_LOAN_TOKEN_BURN);
require(controller.closeBorrowVerify(address(this), _loanOwner, _borrow.loan), Errors.FAIL_CLOSE_BORROW);
//Emit the CloseLoan Event
emit CloseLoan(
_loanOwner,
_borrow.delegatee,
address(underlying),
_borrow.amount,
address(this),
_totalFees,
_loan,
_borrow.tokenId,
false
);
}
/**
* @notice Kill a non-healthy Loan to collect rewards
* @dev Kill a non-healthy Loan to collect rewards
* @param _loan Address of the Loan
*/
function killBorrow(address _loan) public virtual override nonReentrant {
address killer = msg.sender;
//Fetch the corresponding Borrow
//And check that the killer is not the Borrower, and the Loan is still active
Borrow storage _borrow = loanToBorrow[_loan];
require(!_borrow.closed, Errors.LOAN_CLOSED);
require(!isLoanOwner(_loan, killer), Errors.LOAN_OWNER);
require(_updateInterest());
//Get the owner of the Loan through the ERC721 contract
address _loanOwner = palLoanToken.ownerOf(_borrow.tokenId);
//Calculate the amount of fee used, and check if the Loan is killable
uint _feesUsed = (_borrow.amount.mul(borrowIndex).div(_borrow.borrowIndex)).sub(_borrow.amount);
uint _loanHealthFactor = _feesUsed.mul(uint(1e18)).div(_borrow.feesAmount);
require(_loanHealthFactor >= killFactor, Errors.NOT_KILLABLE);
//Load the Loan
IPalLoan _palLoan = IPalLoan(_borrow.loan);
//Close the Loan, and update storage variables
_borrow.closed = true;
_borrow.killed = true;
_borrow.feesUsed = _borrow.feesAmount;
_borrow.closeBlock = block.number;
//Remove the borrowed tokens + fees from the TotalBorrowed
//Remove the amount paid as killer fees from the Reserve, and any over accrued interest in the Reserve & AccruedFees
uint _overAccruedInterest = _loanHealthFactor <= mantissaScale ? 0 : _feesUsed.sub(_borrow.feesAmount);
uint _killerFees = (_borrow.feesAmount).mul(killerRatio).div(mantissaScale);
numberActiveLoans = numberActiveLoans.sub(1);
totalBorrowed = numberActiveLoans == 0 ? 0 : totalBorrowed.sub((_borrow.amount).add(_feesUsed)); //If not current active Loan, we can just reset the totalBorrowed to 0
totalReserve = totalReserve.sub(_killerFees).sub(_overAccruedInterest.mul(reserveFactor).div(mantissaScale));
accruedFees = accruedFees.sub(_overAccruedInterest.mul(reserveFactor.sub(killerRatio)).div(mantissaScale));
//Kill the Loan
_palLoan.killLoan(killer, killerRatio);
//Burn the palLoanToken for this Loan
require(palLoanToken.burn(_borrow.tokenId), Errors.FAIL_LOAN_TOKEN_BURN);
require(controller.killBorrowVerify(address(this), killer, _borrow.loan), Errors.FAIL_KILL_BORROW);
//Emit the CloseLoan Event
emit CloseLoan(
_loanOwner,
_borrow.delegatee,
address(underlying),
_borrow.amount,
address(this),
_borrow.feesAmount,
_loan,
_borrow.tokenId,
true
);
}
/**
* @notice Change the delegatee of a Loan, and delegate him the voting power
* @dev Change the delegatee in the Borrow struct and in the palLoan, then change the voting power delegation recipient
* @param _loan Address of the Loan
* @param _newDelegatee Address of the new voting power recipient
*/
function changeBorrowDelegatee(address _loan, address _newDelegatee) public virtual override nonReentrant {
//Fetch the corresponding Borrow
//And check that the caller is the Borrower, and the Loan is still active
Borrow storage _borrow = loanToBorrow[_loan];
require(!_borrow.closed, Errors.LOAN_CLOSED);
require(_newDelegatee != address(0), Errors.ZERO_ADDRESS);
require(isLoanOwner(_loan, msg.sender), Errors.NOT_LOAN_OWNER);
require(_updateInterest());
//Load the Loan Pool contract
IPalLoan _palLoan = IPalLoan(_borrow.loan);
//Update storage data
_borrow.delegatee = _newDelegatee;
//Call the delegation logic in the palLoan to change the votong power recipient
require(_palLoan.changeDelegatee(_newDelegatee), Errors.FAIL_LOAN_DELEGATEE_CHANGE);
//Emit the Event
emit ChangeLoanDelegatee(
palLoanToken.ownerOf(_borrow.tokenId),
_newDelegatee,
address(underlying),
address(this),
_borrow.loan,
_borrow.tokenId
);
}
/**
* @notice Return the user's palToken balance
* @dev Links the PalToken balanceOf() method
* @param _account User address
* @return uint256 : user palToken balance (in wei)
*/
function balanceOf(address _account) public view override returns(uint){
return palToken.balanceOf(_account);
}
/**
* @notice Return the corresponding balance of the pool underlying token depending on the user's palToken balance
* @param _account User address
* @return uint256 : corresponding balance in the underlying token (in wei)
*/
function underlyingBalanceOf(address _account) external view override returns(uint){
uint _balance = palToken.balanceOf(_account);
if(_balance == 0){
return 0;
}
uint _exchRate = _exchangeRate();
uint _num = _balance.mul(_exchRate);
return _num.div(mantissaScale);
}
/**
* @notice Return true is the given address is the owner of the palLoanToken for the given palLoan
* @param _loanAddress Address of the Loan
* @param _user User address
* @return bool : true if owner
*/
function isLoanOwner(address _loanAddress, address _user) public view override returns(bool){
return palLoanToken.allOwnerOf(idOfLoan(_loanAddress)) == _user;
}
/**
* @notice Return the token Id of the palLoanToken linked to this palLoan
* @param _loanAddress Address of the Loan
* @return uint256 : palLoanToken token Id
*/
function idOfLoan(address _loanAddress) public view override returns(uint256){
return loanToBorrow[_loanAddress].tokenId;
}
/**
* @notice Return the list of all Loans for this Pool (closed and active)
* @return address[] : list of Loans
*/
function getLoansPools() external view override returns(address [] memory){
//Return the addresses of all loans (old ones and active ones)
return loans;
}
/**
* @notice Return all the Loans for a given address
* @param _borrower Address of the user
* @return address : list of Loans
*/
function getLoansByBorrower(address _borrower) external view override returns(address [] memory){
return palLoanToken.allLoansOfForPool(_borrower, address(this));
}
/**
* @notice Return the stored Borrow data for a given Loan
* @dev Return the Borrow data for a given Loan
* @param _loanAddress Address of the palLoan
* Composants of a Borrow struct
*/
function getBorrowData(address _loanAddress) external view override returns(
address _borrower,
address _delegatee,
address _loan,
uint256 _palLoanTokenId,
uint _amount,
address _underlying,
uint _feesAmount,
uint _feesUsed,
uint _startBlock,
uint _closeBlock,
bool _closed,
bool _killed
){
//Return the data inside a Borrow struct
Borrow memory _borrow = loanToBorrow[_loanAddress];
return (
//Get the Loan owner through the ERC721 contract
palLoanToken.allOwnerOf(_borrow.tokenId),
_borrow.delegatee,
_borrow.loan,
_borrow.tokenId,
_borrow.amount,
_borrow.underlying,
_borrow.feesAmount,
//Calculate amount of fees used
_borrow.closed ? _borrow.feesUsed : (_borrow.amount.mul(borrowIndex).div(_borrow.borrowIndex)).sub(_borrow.amount),
_borrow.startBlock,
_borrow.closeBlock,
_borrow.closed,
_borrow.killed
);
}
/**
* @notice Get the Borrow Rate for this Pool
* @dev Get the Borrow Rate from the Interest Module
* @return uint : Borrow Rate (scale 1e18)
*/
function borrowRatePerBlock() external view override returns (uint){
return interestModule.getBorrowRate(address(this), underlyingBalance(), totalBorrowed, totalReserve);
}
/**
* @notice Get the Supply Rate for this Pool
* @dev Get the Supply Rate from the Interest Module
* @return uint : Supply Rate (scale 1e18)
*/
function supplyRatePerBlock() external view override returns (uint){
return interestModule.getSupplyRate(address(this), underlyingBalance(), totalBorrowed, totalReserve, reserveFactor);
}
/**
* @dev Calculates the current exchange rate
* @return uint : current exchange rate (scale 1e18)
*/
function _exchangeRate() internal view returns (uint){
uint _totalSupply = palToken.totalSupply();
//If no palTokens where minted, use the initial exchange rate
if(_totalSupply == 0){
return initialExchangeRate;
}
else{
// Exchange Rate = (Cash + Borrows - Reserve) / Supply
uint _cash = underlyingBalance();
uint _availableCash = _cash.add(totalBorrowed).sub(totalReserve);
return _availableCash.mul(1e18).div(_totalSupply);
}
}
/**
* @notice Get the current exchange rate for the palToken
* @dev Updates interest & Calls internal function _exchangeRate
* @return uint : current exchange rate (scale 1e18)
*/
function exchangeRateCurrent() external override returns (uint){
_updateInterest();
return _exchangeRate();
}
/**
* @notice Get the stored exchange rate for the palToken
* @dev Calls internal function _exchangeRate
* @return uint : current exchange rate (scale 1e18)
*/
function exchangeRateStored() external view override returns (uint){
return _exchangeRate();
}
/**
* @notice Return the minimum of fees to pay to borrow
* @dev Fees to pay for a Borrow (for the minimum borrow length)
* @return uint : minimum amount (in wei)
*/
function minBorrowFees(uint _amount) public view override returns (uint){
require(_amount < underlyingBalance(), Errors.INSUFFICIENT_CASH);
//Future Borrow Rate with the amount to borrow counted as already borrowed
uint _borrowRate = interestModule.getBorrowRate(address(this), underlyingBalance().sub(_amount), totalBorrowed.add(_amount), totalReserve);
uint _minFees = minBorrowLength.mul(_amount.mul(_borrowRate)).div(mantissaScale);
return _minFees > 0 ? _minFees : 1;
}
function isKillable(address _loan) external view override returns(bool){
Borrow memory __borrow = loanToBorrow[_loan];
if(__borrow.closed){
return false;
}
//Calculate the amount of fee used, and check if the Loan is killable
uint _feesUsed = (__borrow.amount.mul(borrowIndex).div(__borrow.borrowIndex)).sub(__borrow.amount);
uint _loanHealthFactor = _feesUsed.mul(uint(1e18)).div(__borrow.feesAmount);
return _loanHealthFactor >= killFactor;
}
/**
* @dev Updates Inetrest and variables for this Pool
* @return bool : Update success
*/
function _updateInterest() public returns (bool){
//Get the current block
//Check if the Pool has already been updated this block
uint _currentBlock = block.number;
if(_currentBlock == accrualBlockNumber){
return true;
}
//Get Pool variables from Storage
uint _cash = underlyingBalance();
uint _borrows = totalBorrowed;
uint _reserves = totalReserve;
uint _accruedFees = accruedFees;
uint _oldBorrowIndex = borrowIndex;
//Get the Borrow Rate from the Interest Module
uint _borrowRate = interestModule.getBorrowRate(address(this), _cash, _borrows, _reserves);
//Delta of blocks since the last update
uint _ellapsedBlocks = _currentBlock.sub(accrualBlockNumber);
/*
Interest Factor = Borrow Rate * Ellapsed Blocks
Accumulated Interests = Interest Factor * Borrows
Total Borrows = Borrows + Accumulated Interests
Total Reserve = Reserve + Accumulated Interests * Reserve Factor
Accrued Fees = Accrued Fees + Accumulated Interests * (Reserve Factor - Killer Ratio) -> (available fees should not count potential fees to send to killers)
Borrow Index = old Borrow Index + old Borrow Index * Interest Factor
*/
uint _interestFactor = _borrowRate.mul(_ellapsedBlocks);
uint _accumulatedInterest = _interestFactor.mul(_borrows).div(mantissaScale);
uint _newBorrows = _borrows.add(_accumulatedInterest);
uint _newReserve = _reserves.add(reserveFactor.mul(_accumulatedInterest).div(mantissaScale));
uint _newAccruedFees = _accruedFees.add((reserveFactor.sub(killerRatio)).mul(_accumulatedInterest).div(mantissaScale));
uint _newBorrowIndex = _oldBorrowIndex.add(_interestFactor.mul(_oldBorrowIndex).div(1e18));
//Update storage
totalBorrowed = _newBorrows;
totalReserve = _newReserve;
accruedFees = _newAccruedFees;
borrowIndex = _newBorrowIndex;
accrualBlockNumber = _currentBlock;
return true;
}
// Admin Functions
/**
* @notice Set a new Controller
* @dev Loads the new Controller for the Pool
* @param _newController address of the new Controller
*/
function setNewController(address _newController) external override controllerOnly {
controller = IPaladinController(_newController);
}
/**
* @notice Set a new Interest Module
* @dev Load a new Interest Module
* @param _interestModule address of the new Interest Module
*/
function setNewInterestModule(address _interestModule) external override adminOnly {
interestModule = InterestInterface(_interestModule);
}
/**
* @notice Set a new Delegator
* @dev Change Delegator address
* @param _delegator address of the new Delegator
*/
function setNewDelegator(address _delegator) external override adminOnly {
delegator = _delegator;
}
/**
* @notice Set a new Minimum Borrow Length
* @dev Change Minimum Borrow Length value
* @param _length new Minimum Borrow Length
*/
function updateMinBorrowLength(uint _length) external override adminOnly {
require(_length > 0, Errors.INVALID_PARAMETERS);
minBorrowLength = _length;
}
/**
* @notice Update the Pool Reserve Factor & Killer Ratio
* @dev Change Reserve Factor value & Killer Ratio value
* @param _reserveFactor new % of fees to set as Reserve
* @param _killerRatio new Ratio of Fees to pay the killer
*/
function updatePoolFactors(uint _reserveFactor, uint _killerRatio) external override adminOnly {
require(_reserveFactor > 0 && _killerRatio > 0 && _reserveFactor >= _killerRatio,
Errors.INVALID_PARAMETERS
);
reserveFactor = _reserveFactor;
killerRatio = _killerRatio;
}
/**
* @notice Add underlying in the Pool Reserve
* @dev Transfer underlying token from the admin to the Pool
* @param _amount Amount of underlying to transfer
*/
function addReserve(uint _amount) external override adminOnly {
require(_updateInterest());
totalReserve = totalReserve.add(_amount);
//Transfer from the admin to the Pool
underlying.safeTransferFrom(admin, address(this), _amount);
emit AddReserve(_amount);
}
/**
* @notice Remove underlying from the Pool Reserve
* @dev Transfer underlying token from the Pool to the admin
* @param _amount Amount of underlying to transfer
*/
function removeReserve(uint _amount) external override adminOnly {
//Check if there is enough in the reserve
require(_updateInterest());
require(_amount <= underlyingBalance() && _amount <= totalReserve, Errors.RESERVE_FUNDS_INSUFFICIENT);
totalReserve = totalReserve.sub(_amount);
//Transfer underlying to the admin
underlying.safeTransfer(admin, _amount);
emit RemoveReserve(_amount);
}
/**
* @notice Method to allow the Controller (or admin) to withdraw protocol fees
* @dev Transfer underlying token from the Pool to the controller (or admin)
* @param _amount Amount of underlying to transfer
* @param _recipient Address to receive the token
*/
function withdrawFees(uint _amount, address _recipient) external override controllerOnly {
//Check if there is enough in the reserve
require(_updateInterest());
require(_amount<= accruedFees && _amount <= totalReserve, Errors.FEES_ACCRUED_INSUFFICIENT);
//Substract from accruedFees (to track how much fees the Controller can withdraw since last time)
//And also from the REserve, since the fees are part of the Reserve
accruedFees = accruedFees.sub(_amount);
totalReserve = totalReserve.sub(_amount);
//Transfer fees to the recipient
underlying.safeTransfer(_recipient, _amount);
emit WithdrawFees(_amount);
}
}
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "./IERC20.sol";
import "./SafeMath.sol";
import "./Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
}
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
pragma abicoder v2;
//SPDX-License-Identifier: MIT
/** @title palPool Interface */
/// @author Paladin
interface IPalPool {
//Events
/** @notice Event when an user deposit tokens in the pool */
event Deposit(address user, uint amount, address palPool);
/** @notice Event when an user withdraw tokens from the pool */
event Withdraw(address user, uint amount, address palPool);
/** @notice Event when a loan is started */
event NewLoan(
address borrower,
address delegatee,
address underlying,
uint amount,
address palPool,
address loanAddress,
uint256 palLoanTokenId,
uint startBlock);
/** @notice Event when the fee amount in the loan is updated */
event ExpandLoan(
address borrower,
address delegatee,
address underlying,
address palPool,
uint newFeesAmount,
address loanAddress,
uint256 palLoanTokenId
);
/** @notice Event when the delegatee of the loan is updated */
event ChangeLoanDelegatee(
address borrower,
address newDelegatee,
address underlying,
address palPool,
address loanAddress,
uint256 palLoanTokenId
);
/** @notice Event when a loan is ended */
event CloseLoan(
address borrower,
address delegatee,
address underlying,
uint amount,
address palPool,
uint usedFees,
address loanAddress,
uint256 palLoanTokenId,
bool wasKilled
);
/** @notice Reserve Events */
event AddReserve(uint amount);
event RemoveReserve(uint amount);
event WithdrawFees(uint amount);
//Functions
function deposit(uint _amount) external returns(uint);
function withdraw(uint _amount) external returns(uint);
function borrow(address _delegatee, uint _amount, uint _feeAmount) external returns(uint);
function expandBorrow(address _loanPool, uint _feeAmount) external returns(uint);
function closeBorrow(address _loanPool) external;
function killBorrow(address _loanPool) external;
function changeBorrowDelegatee(address _loanPool, address _newDelegatee) external;
function balanceOf(address _account) external view returns(uint);
function underlyingBalanceOf(address _account) external view returns(uint);
function isLoanOwner(address _loanAddress, address _user) external view returns(bool);
function idOfLoan(address _loanAddress) external view returns(uint256);
function getLoansPools() external view returns(address [] memory);
function getLoansByBorrower(address _borrower) external view returns(address [] memory);
function getBorrowData(address _loanAddress) external view returns(
address _borrower,
address _delegatee,
address _loanPool,
uint256 _palLoanTokenId,
uint _amount,
address _underlying,
uint _feesAmount,
uint _feesUsed,
uint _startBlock,
uint _closeBlock,
bool _closed,
bool _killed
);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function exchangeRateCurrent() external returns (uint);
function exchangeRateStored() external view returns (uint);
function minBorrowFees(uint _amount) external view returns (uint);
function isKillable(address _loan) external view returns(bool);
//Admin functions :
function setNewController(address _newController) external;
function setNewInterestModule(address _interestModule) external;
function setNewDelegator(address _delegator) external;
function updateMinBorrowLength(uint _length) external;
function updatePoolFactors(uint _reserveFactor, uint _killerRatio) external;
function addReserve(uint _amount) external;
function removeReserve(uint _amount) external;
function withdrawFees(uint _amount, address _recipient) external;
}
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
import "./IPaladinController.sol";
import "./IPalLoanToken.sol";
import "./interests/InterestInterface.sol";
import "./IPalPool.sol";
import "./IPalToken.sol";
import "./utils/IERC20.sol";
/** @title palPool Storage contract */
/// @author Paladin
contract PalPoolStorage {
/** @notice Struct of a Borrow */
struct Borrow {
//id of the palLoanToken
uint256 tokenId;
//address of the delegatee
address delegatee;
//address of the Loan Pool contract holding the loan
address loan;
//amount of the loan
uint amount;
//address of the underlying for this loan
address underlying;
//amount of fees (in the underlying token) paid by the borrower
uint feesAmount;
//amount of fees (in the underlying token) already used
uint feesUsed;
//borrow index at the loan creation
uint borrowIndex;
//start block for the Borrow
uint startBlock;
//block where the Borrow was closed
uint closeBlock;
//false if the loan is active, true if loan was closed or killed
bool closed;
//false when the loan is active, true if the loan was killed
bool killed;
}
//palPool variables & Mappings
/** @notice ERC721 palLoanToken */
IPalLoanToken public palLoanToken;
/** @notice Underlying ERC20 token of this Pool */
IERC20 public underlying;
/** @notice ERC20 palToken for this Pool */
IPalToken public palToken;
/** @dev Boolean to prevent reentry in some functions */
bool internal entered = false;
/** @notice Total of the current Reserve */
uint public totalReserve;
/** @notice Total of underlying tokens "borrowed" (in Loan Pool contracts) */
uint public totalBorrowed;
/** @notice Total fees accrued since last withdraw */
/** (this amount id part of the Reserve : we should always have totalReserve >= accruedFees) */
uint public accruedFees;
/** @notice Minimum duration of a Borrow (in blocks) */
uint public minBorrowLength = 45290;
/** @dev Health Factor to kill a loan */
uint public constant killFactor = 0.95e18;
/** @dev Ratio of the borrow fees to pay the killer of a loan */
uint public killerRatio = 0.1e18;
/** @dev Base value to mint palTokens */
uint internal constant initialExchangeRate = 1e18;
/** @notice Part of the borrows interest to set as Reserves */
uint public reserveFactor = 0.2e18;
/** @notice Last block where the interest where updated for this pool */
uint public accrualBlockNumber;
/** @notice Borrow Index : increase at each interest update to represent borrows interests increasing */
uint public borrowIndex;
/** @dev Scale used to represent decimal values */
uint constant internal mantissaScale = 1e18;
/** @dev Mapping of Loan Pool contract address to Borrow struct */
mapping (address => Borrow) internal loanToBorrow;
/** @dev List of all Loans (active & closed) */
address[] internal loans;
/** @dev Current number of active Loans */
uint public numberActiveLoans;
//Modules
/** @notice Paladin Controller contract */
IPaladinController public controller;
/** @dev Current Inetrest Module */
InterestInterface internal interestModule;
/** @dev Delegator for the underlying governance token */
address internal delegator;
}
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
/** @title Interface for PalLoan contract */
/// @author Paladin
interface IPalLoan {
// Variables
function underlying() external view returns(address);
function amount() external view returns(uint);
function borrower() external view returns(address);
function delegatee() external view returns(address);
function motherPool() external view returns(address);
function feesAmount() external view returns(uint);
// Functions
function initiate(
address _motherPool,
address _borrower,
address _underlying,
address _delegatee,
uint _amount,
uint _feesAmount
) external returns(bool);
function expand(uint _newFeesAmount) external returns(bool);
function closeLoan(uint _usedAmount) external;
function killLoan(address _killer, uint _killerRatio) external;
function changeDelegatee(address _delegatee) external returns(bool);
}
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
/** @title simple PalToken Interface to be used inside the PalPool contract */
/// @author Paladin
interface IPalToken {
function mint(address _user, uint _toMint) external returns(bool);
function burn(address _user, uint _toBurn) external returns(bool);
function balanceOf(address owner) external view returns(uint);
function totalSupply() external view returns (uint256);
}
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
/** @title Paladin Controller Interface */
/// @author Paladin
interface IPaladinController {
//Events
/** @notice Event emitted when a new token & pool are added to the list */
event NewPalPool(address palPool, address palToken);
/** @notice Event emitted when a token & pool are removed from the list */
event RemovePalPool(address palPool, address palToken);
//Functions
function isPalPool(address pool) external view returns(bool);
function getPalTokens() external view returns(address[] memory);
function getPalPools() external view returns(address[] memory);
function setInitialPools(address[] memory palTokens, address[] memory palPools) external returns(bool);
function addNewPool(address palToken, address palPool) external returns(bool);
function removePool(address _palPool) external returns(bool);
function withdrawPossible(address palPool, uint amount) external view returns(bool);
function borrowPossible(address palPool, uint amount) external view returns(bool);
function depositVerify(address palPool, address dest, uint amount) external view returns(bool);
function withdrawVerify(address palPool, address dest, uint amount) external view returns(bool);
function borrowVerify(address palPool, address borrower, address delegatee, uint amount, uint feesAmount, address loanAddress) external view returns(bool);
function expandBorrowVerify(address palPool, address loanAddress, uint newFeesAmount) external view returns(bool);
function closeBorrowVerify(address palPool, address borrower, address loanAddress) external view returns(bool);
function killBorrowVerify(address palPool, address killer, address loanAddress) external view returns(bool);
//Admin functions
function setPoolsNewController(address _newController) external returns(bool);
function withdrawFromPool(address _pool, uint _amount, address _recipient) external returns(bool);
}
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
pragma abicoder v2;
//SPDX-License-Identifier: MIT
import "./utils/IERC721.sol";
/** @title palLoanToken Interface */
/// @author Paladin
interface IPalLoanToken is IERC721 {
//Events
/** @notice Event when a new Loan Token is minted */
event NewLoanToken(address palPool, address indexed owner, address indexed palLoan, uint256 indexed tokenId);
/** @notice Event when a Loan Token is burned */
event BurnLoanToken(address palPool, address indexed owner, address indexed palLoan, uint256 indexed tokenId);
//Functions
function mint(address to, address palPool, address palLoan) external returns(uint256);
function burn(uint256 tokenId) external returns(bool);
function tokenURI(uint256 tokenId) external view returns (string memory);
function tokenOfByIndex(address owner, uint256 tokenIdex) external view returns (uint256);
function loanOf(uint256 tokenId) external view returns(address);
function poolOf(uint256 tokenId) external view returns(address);
function loansOf(address owner) external view returns(address[] memory);
function tokensOf(address owner) external view returns(uint256[] memory);
function loansOfForPool(address owner, address palPool) external view returns(address[] memory);
function allTokensOf(address owner) external view returns(uint256[] memory);
function allLoansOf(address owner) external view returns(address[] memory);
function allLoansOfForPool(address owner, address palPool) external view returns(address[] memory);
function allOwnerOf(uint256 tokenId) external view returns(address);
function isBurned(uint256 tokenId) external view returns(bool);
//Admin functions
function setNewController(address _newController) external;
function setNewBaseURI(string memory _newBaseURI) external;
}
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
/** @title Interest Module Interface */
/// @author Paladin
interface InterestInterface {
function getSupplyRate(address palPool, uint cash, uint borrows, uint reserves, uint reserveFactor) external view returns(uint);
function getBorrowRate(address palPool, uint cash, uint borrows, uint reserves) external view returns(uint);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.7.6;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
/** @title Admin contract */
/// @author Paladin
contract Admin {
/** @notice (Admin) Event when the contract admin is updated */
event NewAdmin(address oldAdmin, address newAdmin);
/** @dev Admin address for this contract */
address payable internal admin;
modifier adminOnly() {
//allows only the admin of this contract to call the function
require(msg.sender == admin, '1');
_;
}
/**
* @notice Set a new Admin
* @dev Changes the address for the admin parameter
* @param _newAdmin address of the new Controller Admin
*/
function setNewAdmin(address payable _newAdmin) external adminOnly {
address _oldAdmin = admin;
admin = _newAdmin;
emit NewAdmin(_oldAdmin, _newAdmin);
}
}
// 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;
}
}
//โโโโโโโ โโโโโโ โโโ โโโโโโ โโโโโโโ โโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โโโ
//โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโ โโโ
//โโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโ โโโโโโโโโโโโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโ
//โโโ โโโ โโโโโโโโโโโโโโ โโโโโโโโโโ โโโโโโ โโโโโ
pragma solidity ^0.7.6;
//SPDX-License-Identifier: MIT
library Errors {
// Admin error
string public constant CALLER_NOT_ADMIN = '1'; // 'The caller must be the admin'
string public constant CALLER_NOT_CONTROLLER = '29'; // 'The caller must be the admin or the controller'
string public constant CALLER_NOT_ALLOWED_POOL = '30'; // 'The caller must be a palPool listed in the controller'
string public constant CALLER_NOT_MINTER = '31';
// ERC20 type errors
string public constant FAIL_TRANSFER = '2';
string public constant FAIL_TRANSFER_FROM = '3';
string public constant BALANCE_TOO_LOW = '4';
string public constant ALLOWANCE_TOO_LOW = '5';
string public constant SELF_TRANSFER = '6';
// PalPool errors
string public constant INSUFFICIENT_CASH = '9';
string public constant INSUFFICIENT_BALANCE = '10';
string public constant FAIL_DEPOSIT = '11';
string public constant FAIL_LOAN_INITIATE = '12';
string public constant FAIL_BORROW = '13';
string public constant ZERO_BORROW = '27';
string public constant BORROW_INSUFFICIENT_FEES = '23';
string public constant LOAN_CLOSED = '14';
string public constant NOT_LOAN_OWNER = '15';
string public constant LOAN_OWNER = '16';
string public constant FAIL_LOAN_EXPAND = '17';
string public constant NOT_KILLABLE = '18';
string public constant RESERVE_FUNDS_INSUFFICIENT = '19';
string public constant FAIL_MINT = '20';
string public constant FAIL_BURN = '21';
string public constant FAIL_WITHDRAW = '24';
string public constant FAIL_CLOSE_BORROW = '25';
string public constant FAIL_KILL_BORROW = '26';
string public constant ZERO_ADDRESS = '22';
string public constant INVALID_PARAMETERS = '28';
string public constant FAIL_LOAN_DELEGATEE_CHANGE = '32';
string public constant FAIL_LOAN_TOKEN_BURN = '33';
string public constant FEES_ACCRUED_INSUFFICIENT = '34';
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "./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.6;
/**
* @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);
}
|
Kill a non-healthy Loan to collect rewards Kill a non-healthy Loan to collect rewards _loan Address of the Loan/Fetch the corresponding BorrowAnd check that the killer is not the Borrower, and the Loan is still activeGet the owner of the Loan through the ERC721 contractCalculate the amount of fee used, and check if the Loan is killableLoad the LoanClose the Loan, and update storage variablesRemove the borrowed tokens + fees from the TotalBorrowedRemove the amount paid as killer fees from the Reserve, and any over accrued interest in the Reserve & AccruedFeesKill the LoanBurn the palLoanToken for this LoanEmit the CloseLoan Event
|
function killBorrow(address _loan) public virtual override nonReentrant {
address killer = msg.sender;
Borrow storage _borrow = loanToBorrow[_loan];
require(!_borrow.closed, Errors.LOAN_CLOSED);
require(!isLoanOwner(_loan, killer), Errors.LOAN_OWNER);
require(_updateInterest());
address _loanOwner = palLoanToken.ownerOf(_borrow.tokenId);
uint _feesUsed = (_borrow.amount.mul(borrowIndex).div(_borrow.borrowIndex)).sub(_borrow.amount);
uint _loanHealthFactor = _feesUsed.mul(uint(1e18)).div(_borrow.feesAmount);
require(_loanHealthFactor >= killFactor, Errors.NOT_KILLABLE);
IPalLoan _palLoan = IPalLoan(_borrow.loan);
_borrow.closed = true;
_borrow.killed = true;
_borrow.feesUsed = _borrow.feesAmount;
_borrow.closeBlock = block.number;
uint _overAccruedInterest = _loanHealthFactor <= mantissaScale ? 0 : _feesUsed.sub(_borrow.feesAmount);
uint _killerFees = (_borrow.feesAmount).mul(killerRatio).div(mantissaScale);
numberActiveLoans = numberActiveLoans.sub(1);
totalReserve = totalReserve.sub(_killerFees).sub(_overAccruedInterest.mul(reserveFactor).div(mantissaScale));
accruedFees = accruedFees.sub(_overAccruedInterest.mul(reserveFactor.sub(killerRatio)).div(mantissaScale));
_palLoan.killLoan(killer, killerRatio);
require(palLoanToken.burn(_borrow.tokenId), Errors.FAIL_LOAN_TOKEN_BURN);
require(controller.killBorrowVerify(address(this), killer, _borrow.loan), Errors.FAIL_KILL_BORROW);
emit CloseLoan(
_loanOwner,
_borrow.delegatee,
address(underlying),
_borrow.amount,
address(this),
_borrow.feesAmount,
_loan,
_borrow.tokenId,
true
);
}
| 548,469
|
./partial_match/3/0xC3B40aca9Ba564948Dfdb90F13D7409766136D1A/sources/MoneyMarket.sol
|
withdraw `amount` of `asset` from sender's account to sender's address withdraw `amount` of `asset` from msg.sender's account to msg.sender asset The market asset to withdraw requestedAmount The amount to withdraw (or -1 for max) return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
|
function withdraw(address asset, uint requestedAmount) public isKYCVerifiedCustomer returns (uint) {
if (paused) {
return fail(Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED);
}
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[msg.sender][asset];
(err, localResults.accountLiquidity, localResults.accountShortfall) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED);
}
(err, localResults.newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber());
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED);
}
(err, localResults.userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED);
}
if (requestedAmount == uint(-1)) {
(err, localResults.withdrawCapacity) = getAssetAmountForValue(asset, localResults.accountLiquidity);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED);
}
localResults.withdrawAmount = min(localResults.withdrawCapacity, localResults.userSupplyCurrent);
localResults.withdrawAmount = requestedAmount;
}
(err, localResults.updatedCash) = sub(localResults.currentCash, localResults.withdrawAmount);
if (requestedAmount == uint(-1)) {
(err, localResults.withdrawCapacity) = getAssetAmountForValue(asset, localResults.accountLiquidity);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED);
}
localResults.withdrawAmount = min(localResults.withdrawCapacity, localResults.userSupplyCurrent);
localResults.withdrawAmount = requestedAmount;
}
(err, localResults.updatedCash) = sub(localResults.currentCash, localResults.withdrawAmount);
} else {
localResults.currentCash = getCash(asset);
if (err != Error.NO_ERROR) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE);
}
(err, localResults.userSupplyUpdated) = sub(localResults.userSupplyCurrent, localResults.withdrawAmount);
if (err != Error.NO_ERROR) {
return fail(Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED);
}
if (!isZeroExp(localResults.accountShortfall)) {
return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT);
}
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED);
}
if (lessThanExp(localResults.accountLiquidity, localResults.ethValueOfWithdrawal) ) {
return fail(Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL);
}
(err, localResults.newTotalSupply) = addThenSub(market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market.interestRateModel.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return failOpaque(FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode);
}
(err, localResults.newBorrowIndex) = calculateInterestIndex(market.borrowIndex, market.borrowRateMantissa, market.blockNumber, getBlockNumber());
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market.interestRateModel.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return failOpaque(FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode);
}
err = doTransferOut(asset, msg.sender, localResults.withdrawAmount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED);
}
} else {
if(withdrawalerr != 0){
}
}
| 5,302,487
|
./partial_match/1/0xcc58b94a56d1788CFfC4Fb7381dF07Fda61Cd90c/sources/OKAMI.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20(unicode"ลkami", unicode"OKAMI") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 2;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 2;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 2;
uint256 _earlySellLiquidityFee = 2;
uint256 _earlySellMarketingFee = 0;
uint256 _earlySellDevFee = 2;
uint256 totalSupply = 1 * 1e12 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 4,272,633
|
// Verified using https://dapp.tools
// hevm: flattened sources of /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/UniswapV3Medianizer.sol
pragma solidity =0.6.7 >=0.4.0 >=0.5.0 >=0.5.0 <0.8.0;
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. (0 - uint128(1)). Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolDerivedState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns a relative timestamp value representing how long, in seconds, the pool has spent between
/// tickLower and tickUpper
/// @dev This timestamp is strictly relative. To get a useful elapsed time (i.e., duration) value, the value returned
/// by this method should be checkpointed externally after a position is minted, and again before a position is
/// burned. Thus the external contract must control the lifecycle of the position.
/// @param tickLower The lower tick of the range for which to get the seconds inside
/// @param tickUpper The upper tick of the range for which to get the seconds inside
/// @return A relative timestamp for how long the pool spent in the tick range
function secondsInside(int24 tickLower, int24 tickUpper) external view returns (uint32);
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return liquidityCumulatives Cumulative liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory liquidityCumulatives);
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/pool/IUniswapV3PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// feeGrowthOutsideX128 values can only be used if the tick is initialized,
/// i.e. if liquidityGross is greater than 0. In addition, these values are only relative and are used to
/// compute snapshots.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns 8 packed tick seconds outside values. See SecondsOutside for more information
function secondsOutside(int24 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the current tick multiplied by seconds elapsed for the life of the pool as of the
/// observation,
/// Returns liquidityCumulative the current liquidity multiplied by seconds elapsed for the life of the pool as of
/// the observation,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 liquidityCumulative,
bool initialized
);
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/interfaces/IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/* import './pool/IUniswapV3PoolImmutables.sol'; */
/* import './pool/IUniswapV3PoolState.sol'; */
/* import './pool/IUniswapV3PoolDerivedState.sol'; */
/* import './pool/IUniswapV3PoolActions.sol'; */
/* import './pool/IUniswapV3PoolOwnerActions.sol'; */
/* import './pool/IUniswapV3PoolEvents.sol'; */
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/libraries/FullMath.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.4.0; */
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(aรbรทdenominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(aรbรทdenominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < (0 - uint256(1)));
result++;
}
}
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/libraries/LowGasSafeMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity 0.6.7; */
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/libraries/PoolAddress.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/libraries/TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0; */
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = (0 - uint256(1)) / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/univ3/libraries/OracleLibrary.sol
// SPDX-License-Identifier: GPL-2.0-or-later
/* pragma solidity >=0.5.0 <0.8.0; */
/* import '../libraries/FullMath.sol'; */
/* import '../libraries/TickMath.sol'; */
/* import '../interfaces/IUniswapV3Pool.sol'; */
/* import '../libraries/LowGasSafeMath.sol'; */
/* import '../libraries/PoolAddress.sol'; */
/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
/// @notice Fetches time-weighted average tick using Uniswap V3 oracle
/// @param pool Address of Uniswap V3 pool that we want to observe
/// @param period Number of seconds in the past to start calculating time-weighted average
/// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp
function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) {
require(period != 0, 'BP');
uint32[] memory secondAgos = new uint32[](2);
secondAgos[0] = period;
secondAgos[1] = 0;
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
timeWeightedAverageTick = int24(tickCumulativesDelta / period);
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) timeWeightedAverageTick--;
}
/// @notice Given a tick and a token amount, calculates the amount of token received in exchange
/// @param tick Tick value used to calculate the quote
/// @param baseAmount Amount of token to be converted
/// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
/// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
/// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) internal pure returns (uint256 quoteAmount) {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
// Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
if (sqrtRatioX96 <= uint128(-1)) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
}
////// /nix/store/jhkj8my1hkpiklhhkl8xyzpxwpzix5fj-geb-uniswap-median/dapp/geb-uniswap-median/src/UniswapV3Medianizer.sol
/* pragma solidity 0.6.7; */
/* import './univ3/interfaces/IUniswapV3Pool.sol'; */
/* import './univ3/libraries/OracleLibrary.sol'; */
abstract contract TokenLike {
function balanceOf(address) public view virtual returns (uint256);
}
contract UniswapV3Medianizer {
// --- Auth ---
mapping (address => uint) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "UniswapV3Medianizer/account-not-authorized");
_;
}
// --- Uniswap Vars ---
// Default amount of targetToken used when calculating the denominationToken output
uint128 public defaultAmountIn = 1 ether;
// Minimum liquidity of targetToken to consider a valid result
uint256 public minimumLiquidity;
// Token for which the contract calculates the medianPrice for
address public targetToken;
// Pair token from the Uniswap pair
address public denominationToken;
// The pool to read price data from
address public uniswapPool;
// --- General Vars ---
// The desired amount of time over which the moving average should be computed, e.g. 24 hours
uint32 public windowSize;
// Manual flag that can be set by governance and indicates if a result is valid or not
uint256 public validityFlag;
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(
bytes32 parameter,
address addr
);
event ModifyParameters(
bytes32 parameter,
uint256 val
);
constructor(
address uniswapPool_,
address targetToken_,
uint32 windowSize_,
uint256 minimumLiquidity_
) public {
require(uniswapPool_ != address(0), "UniswapV3Medianizer/null-uniswap-factory");
require(windowSize_ > 0, 'UniswapV3Medianizer/null-window-size');
authorizedAccounts[msg.sender] = 1;
uniswapPool = uniswapPool_;
windowSize = windowSize_;
minimumLiquidity = minimumLiquidity_;
validityFlag = 1;
targetToken = targetToken_;
address token0 = IUniswapV3Pool(uniswapPool_).token0();
address token1 = IUniswapV3Pool(uniswapPool_).token1();
require(targetToken_ == token0 || targetToken_ == token1, "UniswapV3Medianizer/target-not-from-pool");
denominationToken = targetToken_ == token0 ? token1 : token0;
// Emit events
emit AddAuthorization(msg.sender);
emit ModifyParameters(bytes32("windowSize"), windowSize_);
}
// --- General Utils --
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
function both(bool x, bool y) private pure returns (bool z) {
assembly{ z := and(x, y)}
}
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "UniswapV3Medianizer/toUint128_overflow");
return uint128(value);
}
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "UniswapV3Medianizer/toUint32_overflow");
return uint32(value);
}
// --- Administration ---
/**
* @notice Modify uint256 parameters
* @param parameter Name of the parameter to modify
* @param data New parameter value
**/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "validityFlag") {
require(either(data == 1, data == 0), "UniswapV3Medianizer/invalid-data");
validityFlag = data;
}
else if (parameter == "defaultAmountIn") {
require(data > 0, "UniswapV3Medianizer/invalid-default-amount-in");
defaultAmountIn = toUint128(data);
}
else if (parameter == "windowSize") {
require(data > 0, 'UniswapV3Medianizer/invalid-window-size');
windowSize = toUint32(data);
}
else if (parameter == "minimumLiquidity") {
minimumLiquidity = data;
}
else revert("UniswapV3Medianizer/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
// --- Getters ---
/**
* @notice Returns true if feed is valid
**/
function isValid() public view returns (bool) {
return both(validityFlag == 1, TokenLike(targetToken).balanceOf(address(uniswapPool)) >= minimumLiquidity);
}
/**
* @notice Returns medianPrice for windowSize
**/
function getMedianPrice() public view returns (uint256) {
return getMedianPrice(windowSize);
}
/**
* @notice Returns medianPrice for a given period
* @param period Number of seconds in the past to start calculating time-weighted average
* @return TWAP
**/
function getMedianPrice(uint32 period) public view returns (uint256) {
int24 timeWeightedAverageTick = OracleLibrary.consult(address(uniswapPool), period);
return OracleLibrary.getQuoteAtTick(
timeWeightedAverageTick,
defaultAmountIn,
targetToken,
denominationToken
);
}
/**
* @notice Fetch the latest medianPrice (for maxWindow) or revert if is is null
**/
function read() external view returns (uint256 value) {
value = getMedianPrice();
require(
both(value > 0, isValid()),
"UniswapV3Medianizer/invalid-price-feed"
);
}
/**
* @notice Fetch the latest medianPrice and whether it is null or not
**/
function getResultWithValidity() external view returns (uint256 value, bool valid) {
value = getMedianPrice();
valid = both(value > 0, isValid());
}
}
|
Calculates ceil(aรbรทdenominator) with full precision. Throws if result overflows a uint256 or denominator == 0 a The multiplicand b The multiplier denominator The divisor return result The 256-bit result
|
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < (0 - uint256(1)));
result++;
}
}
| 544,672
|
pragma solidity ^0.4.13;
contract IERC20 {
function balanceOf(
address whom
)
external
view
returns (uint);
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
)
public
returns (bool);
function decimals()
external
view
returns (uint);
function symbol()
external
view
returns (string);
function name()
external
view
returns (string);
function freezeTransfers()
external;
function unfreezeTransfers()
external;
}
contract IStructuredStorage {
function setProxyLogicContractAndDeployer(address _proxyLogicContract, address _deployer) external;
function setProxyLogicContract(address _proxyLogicContract) external;
// *** Getter Methods ***
function getUint(bytes32 _key) external view returns(uint);
function getString(bytes32 _key) external view returns(string);
function getAddress(bytes32 _key) external view returns(address);
function getBytes(bytes32 _key) external view returns(bytes);
function getBool(bytes32 _key) external view returns(bool);
function getInt(bytes32 _key) external view returns(int);
function getBytes32(bytes32 _key) external view returns(bytes32);
// *** Getter Methods For Arrays ***
function getBytes32Array(bytes32 _key) external view returns (bytes32[]);
function getAddressArray(bytes32 _key) external view returns (address[]);
function getUintArray(bytes32 _key) external view returns (uint[]);
function getIntArray(bytes32 _key) external view returns (int[]);
function getBoolArray(bytes32 _key) external view returns (bool[]);
// *** Setter Methods ***
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string _value) external;
function setAddress(bytes32 _key, address _value) external;
function setBytes(bytes32 _key, bytes _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// *** Setter Methods For Arrays ***
function setBytes32Array(bytes32 _key, bytes32[] _value) external;
function setAddressArray(bytes32 _key, address[] _value) external;
function setUintArray(bytes32 _key, uint[] _value) external;
function setIntArray(bytes32 _key, int[] _value) external;
function setBoolArray(bytes32 _key, bool[] _value) external;
// *** Delete Methods ***
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteAddress(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
}
contract ITether {
function transferFrom(address _from, address _to, uint256 _value) external;
function transfer(address _to, uint256 _value) external;
}
contract ITwoKeyAdmin {
function getDefaultIntegratorFeePercent() public view returns (uint);
function getDefaultNetworkTaxPercent() public view returns (uint);
function getTwoKeyRewardsReleaseDate() external view returns(uint);
function updateReceivedTokensAsModerator(uint amountOfTokens) public;
function updateReceivedTokensAsModeratorPPC(uint amountOfTokens, address campaignPlasma) public;
function addFeesCollectedInCurrency(string currency, uint amount) public payable;
function updateTokensReceivedFromDistributionFees(uint amountOfTokens) public;
}
contract ITwoKeyEventSource {
function ethereumOf(address me) public view returns (address);
function plasmaOf(address me) public view returns (address);
function isAddressMaintainer(address _maintainer) public view returns (bool);
function getTwoKeyDefaultIntegratorFeeFromAdmin() public view returns (uint);
function joined(address _campaign, address _from, address _to) external;
function rejected(address _campaign, address _converter) external;
function convertedAcquisition(
address _campaign,
address _converterPlasma,
uint256 _baseTokens,
uint256 _bonusTokens,
uint256 _conversionAmount,
bool _isFiatConversion,
uint _conversionId
)
external;
function getTwoKeyDefaultNetworkTaxPercent()
public
view
returns (uint);
function convertedDonation(
address _campaign,
address _converterPlasma,
uint256 _conversionAmount,
uint256 _conversionId
)
external;
function executed(
address _campaignAddress,
address _converterPlasmaAddress,
uint _conversionId,
uint tokens
)
external;
function tokensWithdrawnFromPurchasesHandler(
address campaignAddress,
uint _conversionID,
uint _tokensAmountWithdrawn
)
external;
function emitDebtEvent(
address _plasmaAddress,
uint _amount,
bool _isAddition,
string _currency
)
external;
function emitReceivedTokensToDeepFreezeTokenPool(
address _campaignAddress,
uint _amountOfTokens
)
public;
function emitReceivedTokensAsModerator(
address _campaignAddress,
uint _amountOfTokens
)
public;
function emitDAIReleasedAsIncome(
address _campaignContractAddress,
uint _amountOfDAI
)
public;
function emitEndedBudgetCampaign(
address campaignPlasmaAddress,
uint contractorLeftover,
uint moderatorEarningsDistributed
)
public;
function emitUserWithdrawnNetworkEarnings(
address user,
uint amountOfTokens
)
public;
function emitRebalancedRewards(
uint cycleId,
uint difference,
string action
)
public;
}
contract ITwoKeyExchangeRateContract {
function getBaseToTargetRate(string _currency) public view returns (uint);
function getStableCoinTo2KEYQuota(address stableCoinAddress) public view returns (uint,uint);
function getStableCoinToUSDQuota(address stableCoin) public view returns (uint);
}
contract ITwoKeyMaintainersRegistry {
function checkIsAddressMaintainer(address _sender) public view returns (bool);
function checkIsAddressCoreDev(address _sender) public view returns (bool);
function addMaintainers(address [] _maintainers) public;
function addCoreDevs(address [] _coreDevs) public;
function removeMaintainers(address [] _maintainers) public;
function removeCoreDevs(address [] _coreDevs) public;
}
contract ITwoKeySingletoneRegistryFetchAddress {
function getContractProxyAddress(string _contractName) public view returns (address);
function getNonUpgradableContractAddress(string contractName) public view returns (address);
function getLatestCampaignApprovedVersion(string campaignType) public view returns (string);
}
interface ITwoKeySingletonesRegistry {
/**
* @dev This event will be emitted every time a new proxy is created
* @param proxy representing the address of the proxy created
*/
event ProxyCreated(address proxy);
/**
* @dev This event will be emitted every time a new implementation is registered
* @param version representing the version name of the registered implementation
* @param implementation representing the address of the registered implementation
* @param contractName is the name of the contract we added new version
*/
event VersionAdded(string version, address implementation, string contractName);
/**
* @dev Registers a new version with its implementation address
* @param version representing the version name of the new implementation to be registered
* @param implementation representing the address of the new implementation to be registered
*/
function addVersion(string _contractName, string version, address implementation) public;
/**
* @dev Tells the address of the implementation for a given version
* @param _contractName is the name of the contract we're querying
* @param version to query the implementation of
* @return address of the implementation registered for the given version
*/
function getVersion(string _contractName, string version) public view returns (address);
}
contract IUpgradableExchange {
function buyRate2key() public view returns (uint);
function sellRate2key() public view returns (uint);
function buyTokensWithERC20(
uint amountOfTokens,
address tokenAddress
)
public
returns (uint,uint);
function buyTokens(
address _beneficiary
)
public
payable
returns (uint,uint);
function buyStableCoinWith2key(
uint _twoKeyUnits,
address _beneficiary
)
public
payable;
function report2KEYWithdrawnFromNetwork(
uint amountOfTokensWithdrawn
)
public;
function getEth2DaiAverageExchangeRatePerContract(
uint _contractID
)
public
view
returns (uint);
function getContractId(
address _contractAddress
)
public
view
returns (uint);
function getEth2KeyAverageRatePerContract(
uint _contractID
)
public
view
returns (uint);
function returnLeftoverAfterRebalancing(
uint amountOf2key
)
public;
function getMore2KeyTokensForRebalancing(
uint amountOf2KeyRequested
)
public
view
returns (uint);
function releaseAllDAIFromContractToReserve()
public;
function setKyberReserveInterfaceContractAddress(
address kyberReserveContractAddress
)
public;
function setSpreadWei(
uint newSpreadWei
)
public;
function withdrawDAIAvailableToFill2KEYReserve(
uint amountOfDAI
)
public
returns (uint);
function returnTokensBackToExchangeV1(
uint amountOfTokensToReturn
)
public;
function getMore2KeyTokensForRebalancingV1(
uint amountOfTokensRequested
)
public;
}
contract ITwoKeyBudgetCampaignsPaymentsHandlerStorage is IStructuredStorage{
}
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;
require(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) {
require(_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;
require(c >= _a);
return c;
}
}
contract ITwoKeySingletonUtils {
address public TWO_KEY_SINGLETON_REGISTRY;
// Modifier to restrict method calls only to maintainers
modifier onlyMaintainer {
address twoKeyMaintainersRegistry = getAddressFromTwoKeySingletonRegistry("TwoKeyMaintainersRegistry");
require(ITwoKeyMaintainersRegistry(twoKeyMaintainersRegistry).checkIsAddressMaintainer(msg.sender));
_;
}
/**
* @notice Function to get any singleton contract proxy address from TwoKeySingletonRegistry contract
* @param contractName is the name of the contract we're looking for
*/
function getAddressFromTwoKeySingletonRegistry(
string contractName
)
internal
view
returns (address)
{
return ITwoKeySingletoneRegistryFetchAddress(TWO_KEY_SINGLETON_REGISTRY)
.getContractProxyAddress(contractName);
}
function getNonUpgradableContractAddressFromTwoKeySingletonRegistry(
string contractName
)
internal
view
returns (address)
{
return ITwoKeySingletoneRegistryFetchAddress(TWO_KEY_SINGLETON_REGISTRY)
.getNonUpgradableContractAddress(contractName);
}
}
contract UpgradeabilityStorage {
// Versions registry
ITwoKeySingletonesRegistry internal registry;
// Address of the current implementation
address internal _implementation;
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address) {
return _implementation;
}
}
contract Upgradeable is UpgradeabilityStorage {
/**
* @dev Validates the caller is the versions registry.
* @param sender representing the address deploying the initial behavior of the contract
*/
function initialize(address sender) public payable {
require(msg.sender == address(registry));
}
}
contract TwoKeyBudgetCampaignsPaymentsHandler is Upgradeable, ITwoKeySingletonUtils {
using SafeMath for *;
/**
* State variables
* TO BE EXPANDED
*/
string constant _campaignPlasma2initialBudget2Key = "campaignPlasma2initialBudget2Key";
string constant _campaignPlasma2isCampaignEnded = "campaignPlasma2isCampaignEnded";
string constant _campaignPlasma2contractor = "campaignPlasma2contractor";
string constant _campaignPlasma2isBudgetedWith2KeyDirectly = "campaignPlasma2isBudgetedWith2KeyDirectly";
string constant _campaignPlasma2StableCoinAddress = "campaignPlasma2StableCoinAddress";
string constant _campaignPlasma2rebalancingRatio = "campaignPlasma2rebalancingRatio";
string constant _campaignPlasma2initialRate = "campaignPlasma2initalRate";
string constant _campaignPlasma2bountyPerConversion2KEY = "campaignPlasma2bountyPerConversion2KEY";
string constant _campaignPlasma2amountOfStableCoins = "campaignPlasma2amountOfStableCoins";
string constant _numberOfDistributionCycles = "numberOfDistributionCycles";
string constant _distributionCycleToTotalDistributed = "_distributionCycleToTotalDistributed";
string constant _campaignPlasma2ReferrerRewardsTotal = "campaignPlasma2ReferrerRewardsTotal";
string constant _campaignPlasmaToModeratorEarnings = "campaignPlasmaToModeratorEarnings";
string constant _campaignPlasmaToLeftOverForContractor = "campaignPlasmaToLeftOverForContractor";
string constant _campaignPlasmaToLeftoverWithdrawnByContractor = "campaignPlasmaToLeftoverWithdrawnByContractor";
string constant _feePerCycleIdPerReferrer = "feePerCycleIdPerReferrer";
ITwoKeyBudgetCampaignsPaymentsHandlerStorage public PROXY_STORAGE_CONTRACT;
bool initialized;
function setInitialParams(
address _twoKeySingletonRegistry,
address _proxyStorageContract
)
public
{
require(initialized == false);
TWO_KEY_SINGLETON_REGISTRY = _twoKeySingletonRegistry;
PROXY_STORAGE_CONTRACT = ITwoKeyBudgetCampaignsPaymentsHandlerStorage(_proxyStorageContract);
initialized = true;
}
/**
* ------------------------------------
* Contractor actions
* ------------------------------------
*/
/**
* @notice Function which will be used in order to add inventory for campaign
* directly with 2KEY tokens. In order to make this
* transfer secure,
* user will firstly have to approve this contract to take from him
* amount of tokens and then call contract function which will execute
* transferFrom action. This function can be called only once.
*
* @param campaignPlasma is the plasma campaign address which is user adding inventory for.
* @param amountOf2KEYTokens is the amount of 2KEY tokens user adds to budget
*/
function addInventory2KEY(
address campaignPlasma,
uint amountOf2KEYTokens,
uint bountyPerConversionFiat
)
public
{
// Require that budget is not previously set and assign amount of 2KEY tokens
requireBudgetNotSetAndSetBudget(campaignPlasma, amountOf2KEYTokens);
// Set that contractor is the msg.sender of this method for the campaign passed
setAddress(keccak256(_campaignPlasma2contractor, campaignPlasma), msg.sender);
// Get 2KEY sell rate at the moment
uint rate = IUpgradableExchange(getAddressFromTwoKeySingletonRegistry("TwoKeyUpgradableExchange")).sellRate2key();
// calculate bounty per conversion 2KEY
uint bountyPerConversion2KEY = bountyPerConversionFiat.mul(10**18).div(rate);
// Calculate and set bounty per conversion in 2KEY units
setUint(
keccak256(_campaignPlasma2bountyPerConversion2KEY, campaignPlasma),
bountyPerConversion2KEY
);
// Set rate at which 2KEY is put to campaign
setUint(
keccak256(_campaignPlasma2initialRate, campaignPlasma),
rate
);
// Set that campaign is budgeted directly with 2KEY tokens
setBool(
keccak256(_campaignPlasma2isBudgetedWith2KeyDirectly, campaignPlasma),
true
);
// Take 2KEY tokens from the contractor
IERC20(getNonUpgradableContractAddressFromTwoKeySingletonRegistry("TwoKeyEconomy")).transferFrom(
msg.sender,
address(this),
amountOf2KEYTokens
);
}
/**
* @notice Function which will be used in order to add inventory for campaign
* directly with stable coin tokens. In order to make this
* transfer secure,
* user will firstly have to approve this contract to take from him
* amount of tokens and then call contract function which will execute
* transferFrom action. This function can be called only once.
*
* @param campaignPlasma is the plasma campaign address which is user adding inventory for.
* @param amountOfStableCoins is the amount of stable coins user adds to budget
* @param tokenAddress is stableCoinAddress
*/
function addInventory(
address campaignPlasma,
uint amountOfStableCoins,
uint bountyPerConversionFiat,
address tokenAddress
)
public
{
// Set that contractor is the msg.sender of this method for the campaign passed
setAddress(keccak256(_campaignPlasma2contractor, campaignPlasma), msg.sender);
address twoKeyUpgradableExchange = getAddressFromTwoKeySingletonRegistry("TwoKeyUpgradableExchange");
// Handle case for Tether due to different ERC20 interface it has
if (tokenAddress == getNonUpgradableContractAddressFromTwoKeySingletonRegistry("USDT")) {
// Take stable coins from the contractor and directly transfer them to upgradable exchange
ITether(tokenAddress).transferFrom(
msg.sender,
twoKeyUpgradableExchange,
amountOfStableCoins
);
} else {
// Take stable coins from the contractor and directly transfer them to upgradable exchange
IERC20(tokenAddress).transferFrom(
msg.sender,
twoKeyUpgradableExchange,
amountOfStableCoins
);
}
uint totalTokensBought;
uint tokenPrice;
// Buy tokens
(totalTokensBought, tokenPrice) = IUpgradableExchange(twoKeyUpgradableExchange).buyTokensWithERC20(amountOfStableCoins, tokenAddress);
// Calculate and set bounty per conversion in 2KEY units
uint bountyPerConversion2KEY = bountyPerConversionFiat.mul(10 ** 18).div(tokenPrice);
// Require that budget is not previously set and set initial budget to amount of 2KEY tokens
requireBudgetNotSetAndSetBudget(campaignPlasma, totalTokensBought);
// SSTORE 20k gas * 3 = 60k 3x uint ==> 256 bytes * 3 * 8 = 6144 gas
// 375 gas + 5 gas for each byte
// 10% 60000 - 6144 = 53856 saving
setUint(
keccak256(_campaignPlasma2bountyPerConversion2KEY, campaignPlasma),
bountyPerConversion2KEY
);
setUint(
keccak256(_campaignPlasma2amountOfStableCoins, campaignPlasma),
amountOfStableCoins
);
// Set stable coin which is used to budget campaign
setAddress(
keccak256(_campaignPlasma2StableCoinAddress, campaignPlasma),
tokenAddress
);
// Set the rate at which we have bought 2KEY tokens
setUint(
keccak256(_campaignPlasma2initialRate, campaignPlasma),
tokenPrice
);
}
/**
* @notice Function where contractor can withdraw if there's any leftover on his campaign
* @param campaignPlasmaAddress is plasma address of campaign
*/
function withdrawLeftoverForContractor(
address campaignPlasmaAddress
)
public
{
// Require that this function is possible to call only by contractor
require(
getAddress(keccak256(_campaignPlasma2contractor,campaignPlasmaAddress)) == msg.sender
);
// Get the leftover for contractor
uint leftoverForContractor = getUint(
keccak256(_campaignPlasmaToLeftOverForContractor, campaignPlasmaAddress)
);
// Check that he has some leftover which can be zero in case that campaign is not ended yet
require(leftoverForContractor > 0);
// Generate key if contractor have withdrawn his leftover for specific campaign
bytes32 key = keccak256(_campaignPlasmaToLeftoverWithdrawnByContractor, campaignPlasmaAddress);
// Require that he didn't withdraw it
require(getBool(key) == false);
// State that now he has withdrawn the tokens.
setBool(key, true);
transfer2KEY(
msg.sender,
leftoverForContractor
);
}
/**
* ------------------------------------
* Maintainer actions
* ------------------------------------
*/
/**
* @notice Function to end selected budget campaign by maintainer, and perform
* actions regarding rebalancing, reserving tokens, and distributing
* moderator earnings, as well as calculating leftover for contractor
*
* @param campaignPlasma is the plasma address of the campaign
* @param totalAmountForReferrerRewards is the total amount before rebalancing referrers earned
* @param totalAmountForModeratorRewards is the total amount moderator earned before rebalancing
*/
function endCampaignReserveTokensAndRebalanceRates(
address campaignPlasma,
uint totalAmountForReferrerRewards,
uint totalAmountForModeratorRewards
)
public
onlyMaintainer
{
// Generate key for storage variable isCampaignEnded
bytes32 keyIsCampaignEnded = keccak256(_campaignPlasma2isCampaignEnded, campaignPlasma);
// Require that campaign is not ended yet
require(getBool(keyIsCampaignEnded) == false);
// End campaign
setBool(keyIsCampaignEnded, true);
// Get how many tokens were inserted at the beginning
uint initialBountyForCampaign = getInitialBountyForCampaign(campaignPlasma);
// Rebalancing everything except referrer rewards
uint amountToRebalance = initialBountyForCampaign.sub(totalAmountForReferrerRewards);
// Amount after rebalancing is initially amount to rebalance
uint amountAfterRebalancing = amountToRebalance;
// Initially rebalanced moderator rewards are total moderator rewards
uint rebalancedModeratorRewards = totalAmountForModeratorRewards;
// Initial ratio is 1
uint rebalancingRatio = 10**18;
if(getIsCampaignBudgetedDirectlyWith2KEY(campaignPlasma) == false) {
// If budget added as stable coin we do rebalancing
(amountAfterRebalancing, rebalancingRatio)
= rebalanceRates(
getInitial2KEYRateForCampaign(campaignPlasma),
amountToRebalance
);
rebalancedModeratorRewards = totalAmountForModeratorRewards.mul(rebalancingRatio).div(10**18);
}
uint leftoverForContractor = amountAfterRebalancing.sub(rebalancedModeratorRewards);
// Set moderator earnings for this campaign and immediately distribute them
setAndDistributeModeratorEarnings(campaignPlasma, rebalancedModeratorRewards);
// Set total amount to use for referrers
setUint(
keccak256(_campaignPlasma2ReferrerRewardsTotal, campaignPlasma),
totalAmountForReferrerRewards
);
// Leftover for contractor
setUint(
keccak256(_campaignPlasmaToLeftOverForContractor, campaignPlasma),
leftoverForContractor
);
// Set rebalancing ratio for campaign
setRebalancingRatioForCampaign(campaignPlasma, rebalancingRatio);
// Emit an event to checksum all the balances per campaign
ITwoKeyEventSource(getAddressFromTwoKeySingletonRegistry("TwoKeyEventSource"))
.emitEndedBudgetCampaign(
campaignPlasma,
leftoverForContractor,
rebalancedModeratorRewards
);
}
/**
* @notice Function to distribute rewards between influencers, increment global cycle id,
* and update how much rewards are ever being distributed from this contract
*
* @param influencers is the array of influencers
* @param balances is the array of corresponding balances for the influencers above
*
*/
function pushAndDistributeRewardsBetweenInfluencers(
address [] influencers,
uint [] balances,
uint nonRebalancedTotalPayout,
uint rebalancedTotalPayout,
uint cycleId,
uint feePerReferrerIn2KEY
)
public
onlyMaintainer
{
// Get the address of 2KEY token
address twoKeyEconomy = getNonUpgradableContractAddressFromTwoKeySingletonRegistry("TwoKeyEconomy");
// Get the address of twoKeyUpgradableExchange contract
address twoKeyUpgradableExchange = getAddressFromTwoKeySingletonRegistry("TwoKeyUpgradableExchange");
// Total distributed in cycle
uint totalDistributed;
// Iterator
uint i;
uint difference;
// Leads to we need to return some tokens back to Upgradable Exchange
if(nonRebalancedTotalPayout > rebalancedTotalPayout) {
difference = nonRebalancedTotalPayout.sub(rebalancedTotalPayout);
IERC20(twoKeyEconomy).approve(twoKeyUpgradableExchange, difference);
IUpgradableExchange(twoKeyUpgradableExchange).returnTokensBackToExchangeV1(difference);
ITwoKeyEventSource(getAddressFromTwoKeySingletonRegistry("TwoKeyEventSource")).emitRebalancedRewards(
cycleId,
difference,
"RETURN_TOKENS_TO_EXCHANGE"
);
} else if (nonRebalancedTotalPayout < rebalancedTotalPayout) {
// Leads to we need to get more tokens from Upgradable Exchange
difference = rebalancedTotalPayout.sub(nonRebalancedTotalPayout);
IUpgradableExchange(twoKeyUpgradableExchange).getMore2KeyTokensForRebalancingV1(difference);
ITwoKeyEventSource(getAddressFromTwoKeySingletonRegistry("TwoKeyEventSource")).emitRebalancedRewards(
cycleId,
difference,
"GET_TOKENS_FROM_EXCHANGE"
);
}
uint numberOfReferrers = influencers.length;
// Iterate through all influencers, distribute them rewards, and account amount received per cycle id
for (i = 0; i < numberOfReferrers; i++) {
// Require that referrer earned more than fees
require(balances[i] > feePerReferrerIn2KEY);
// Sub fee per referrer from balance to pay
uint balance = balances[i].sub(feePerReferrerIn2KEY);
// Transfer required tokens to influencer
IERC20(twoKeyEconomy).transfer(influencers[i], balance);
// Sum up to totalDistributed to referrers
totalDistributed = totalDistributed.add(balance);
}
transferFeesToAdmin(feePerReferrerIn2KEY, numberOfReferrers, twoKeyEconomy);
// Set how much is total distributed per distribution cycle
setUint(
keccak256(_distributionCycleToTotalDistributed, cycleId),
totalDistributed
);
}
/**
* ------------------------------------------------
* Internal functions performing logic operations
* ------------------------------------------------
*/
/**
* @notice Function to transfer fees taken from referrer rewards to admin contract
* @param feePerReferrer is fee taken per referrer equaling 0.5$ in 2KEY at the moment
* @param numberOfReferrers is number of referrers being rewarded in this cycle
* @param twoKeyEconomy is 2KEY token contract
*/
function transferFeesToAdmin(
uint feePerReferrer,
uint numberOfReferrers,
address twoKeyEconomy
)
internal
{
address twoKeyAdmin = getAddressFromTwoKeySingletonRegistry("TwoKeyAdmin");
IERC20(twoKeyEconomy).transfer(
twoKeyAdmin,
feePerReferrer.mul(numberOfReferrers)
);
// Update in admin tokens receiving from fees
ITwoKeyAdmin(twoKeyAdmin).updateTokensReceivedFromDistributionFees(feePerReferrer.mul(numberOfReferrers));
}
/**
* @notice Function to set how many tokens are being distributed to moderator
* as well as distribute them.
* @param campaignPlasma is the plasma address of selected campaign
* @param rebalancedModeratorRewards is the amount for moderator after rebalancing
*/
function setAndDistributeModeratorEarnings(
address campaignPlasma,
uint rebalancedModeratorRewards
)
internal
{
// Account amount moderator earned on this campaign
setUint(
keccak256(_campaignPlasmaToModeratorEarnings, campaignPlasma),
rebalancedModeratorRewards
);
// Get twoKeyAdmin address
address twoKeyAdmin = getAddressFromTwoKeySingletonRegistry("TwoKeyAdmin");
// Transfer 2KEY tokens to moderator
transfer2KEY(
twoKeyAdmin,
rebalancedModeratorRewards
);
// Update moderator on received tokens so it can proceed distribution to TwoKeyDeepFreezeTokenPool
ITwoKeyAdmin(twoKeyAdmin).updateReceivedTokensAsModeratorPPC(rebalancedModeratorRewards, campaignPlasma);
}
/**
* @notice Function to require that initial budget is not set, which
* will prevent any way of adding inventory to specific campaigns
* after it's first time added
* @param campaignPlasma is campaign plasma address
*/
function requireBudgetNotSetAndSetBudget(
address campaignPlasma,
uint amount2KEYTokens
)
internal
{
bytes32 keyHashForInitialBudget = keccak256(_campaignPlasma2initialBudget2Key, campaignPlasma);
// Require that initial budget is not being added, since it can be done only once.
require(getUint(keyHashForInitialBudget) == 0);
// Set initial budget added
setUint(keyHashForInitialBudget, amount2KEYTokens);
}
function rebalanceRates(
uint initial2KEYRate,
uint amountOfTokensToRebalance
)
internal
returns (uint,uint)
{
// Load twoKeyEconomy address
address twoKeyEconomy = getNonUpgradableContractAddressFromTwoKeySingletonRegistry("TwoKeyEconomy");
// Load twoKeyUpgradableExchange address
address twoKeyUpgradableExchange = getAddressFromTwoKeySingletonRegistry("TwoKeyUpgradableExchange");
// Take the current usd to 2KEY rate against we're rebalancing contractor leftover and moderator rewards
uint usd2KEYRateWeiNow = IUpgradableExchange(twoKeyUpgradableExchange).sellRate2key();
// Ratio is initial rate divided by new rate, so if rate went up, this will be less than 1
uint rebalancingRatio = initial2KEYRate.mul(10**18).div(usd2KEYRateWeiNow);
// Calculate new rebalanced amount of tokens
uint rebalancedAmount = amountOfTokensToRebalance.mul(rebalancingRatio).div(10**18);
// If price went up, leads to ratio is going to be less than 10**18
if(rebalancingRatio < 10**18) {
// Calculate how much tokens should be given back to exchange
uint tokensToGiveBackToExchange = amountOfTokensToRebalance.sub(rebalancedAmount);
// Approve upgradable exchange to take leftover back
IERC20(twoKeyEconomy).approve(twoKeyUpgradableExchange, tokensToGiveBackToExchange);
// Call the function to release all DAI for this contract to reserve and to take approved amount of 2key back to liquidity pool
IUpgradableExchange(twoKeyUpgradableExchange).returnTokensBackToExchangeV1(tokensToGiveBackToExchange);
}
// Otherwise we assume that price went down, which leads that ratio will be greater than 10**18
else {
uint tokensToTakeFromExchange = rebalancedAmount.sub(amountOfTokensToRebalance);
// Get more tokens we need
IUpgradableExchange(twoKeyUpgradableExchange).getMore2KeyTokensForRebalancingV1(tokensToTakeFromExchange);
}
// Return new rebalanced amount as well as ratio against which rebalancing was done.
return (rebalancedAmount, rebalancingRatio);
}
/**
* ------------------------------------------------
* Internal getters and setters
* ------------------------------------------------
*/
function getUint(
bytes32 key
)
internal
view
returns (uint)
{
return PROXY_STORAGE_CONTRACT.getUint(key);
}
function setUint(
bytes32 key,
uint value
)
internal
{
PROXY_STORAGE_CONTRACT.setUint(key,value);
}
function getBool(
bytes32 key
)
internal
view
returns (bool)
{
return PROXY_STORAGE_CONTRACT.getBool(key);
}
function setBool(
bytes32 key,
bool value
)
internal
{
PROXY_STORAGE_CONTRACT.setBool(key,value);
}
function getAddress(
bytes32 key
)
internal
view
returns (address)
{
return PROXY_STORAGE_CONTRACT.getAddress(key);
}
function setAddress(
bytes32 key,
address value
)
internal
{
PROXY_STORAGE_CONTRACT.setAddress(key,value);
}
function equals(
string a,
string b
)
internal
pure
returns (bool) {
return keccak256(a) == keccak256(b) ? true : false;
}
/**
* @notice Function whenever called, will increment number of distribution cycles
*/
function incrementNumberOfDistributionCycles()
internal
{
bytes32 key = keccak256(_numberOfDistributionCycles);
setUint(key,getUint(key) + 1);
}
/**
* @notice Function to transfer 2KEY tokens
*
* @param receiver is the address of tokens receiver
* @param amount is the amount of tokens to be transfered
*/
function transfer2KEY(
address receiver,
uint amount
)
internal
{
IERC20(getNonUpgradableContractAddressFromTwoKeySingletonRegistry("TwoKeyEconomy")).transfer(
receiver,
amount
);
}
/**
* @notice Internal setter function to store how much stable coins were
* added to fund this campaign
* @param campaignPlasma is plasma campaign address
* @param amountOfStableCoins is the amount used for campaign funding
*/
function setAmountOfStableCoinsUsedToFundCampaign(
address campaignPlasma,
uint amountOfStableCoins
)
internal
{
setUint(
keccak256(_campaignPlasma2amountOfStableCoins, campaignPlasma),
amountOfStableCoins
);
}
function setRebalancingRatioForCampaign(
address campaignPlasma,
uint rebalancingRatio
)
internal
{
setUint(
keccak256(_campaignPlasma2rebalancingRatio, campaignPlasma),
rebalancingRatio
);
}
/**
* ------------------------------------------------
* Public getters
* ------------------------------------------------
*/
/**
* @notice Function to return rebalancing ratio for specific campaign,
* in case campaign was funded with 2KEY will return 1 ETH as neutral
* @param campaignPlasma is plasma campaign address
*/
function getRebalancingRatioForCampaign(
address campaignPlasma
)
public
view
returns (uint)
{
uint ratio = getUint(keccak256(_campaignPlasma2rebalancingRatio, campaignPlasma));
return ratio != 0 ? ratio : 10**18;
}
/**
* @notice Function to get number of distribution cycles ever
*/
function getNumberOfCycles()
public
view
returns (uint)
{
return getUint(keccak256(_numberOfDistributionCycles));
}
/**
* @notice Function to get how much was initial bounty for selected camapaign in 2KEY tokens
*
* @param campaignPlasma is the plasma address of the campaign
*/
function getInitialBountyForCampaign(
address campaignPlasma
)
public
view
returns (uint)
{
return getUint(keccak256(_campaignPlasma2initialBudget2Key, campaignPlasma));
}
/**
* @notice Function to retrieve the initial rate at which 2KEY tokens were bought if
* were bought at all. Otherwise it returns 0.
* @param campaignPlasma is plasma address of the campaign
*/
function getInitial2KEYRateForCampaign(
address campaignPlasma
)
public
view
returns (uint)
{
return getUint(keccak256(_campaignPlasma2initialRate, campaignPlasma));
}
/**
* @notice Function to get how much is distributed in cycle
* @param cycleId is the ID of that cycle
*/
function getTotalDistributedInCycle(
uint cycleId
)
public
view
returns (uint)
{
return getUint(keccak256(_distributionCycleToTotalDistributed, cycleId));
}
/**
* @notice Function to get moderator rebalanced earnings for this campaign
* @param campaignAddress is plasma campaign address
*/
function getModeratorEarningsRebalancedForCampaign(
address campaignAddress
)
public
view
returns (uint)
{
return (
getUint(keccak256(_campaignPlasmaToModeratorEarnings, campaignAddress)) //moderator earnings)
);
}
/**
* @notice Function to get contractor rebalanced leftover for campaign
* @param campaignAddress is plasma campaign address
*/
function getContractorRebalancedLeftoverForCampaign(
address campaignAddress
)
public
view
returns (uint)
{
return (
getUint(keccak256(_campaignPlasmaToLeftOverForContractor, campaignAddress)) // contractor leftover
);
}
/**
* @notice Function to get moderator earnings and contractor leftover after we rebalanced campaign
* @param campaignAddress is the address of campaign
*/
function getModeratorEarningsAndContractorLeftoverRebalancedForCampaign(
address campaignAddress
)
public
view
returns (uint,uint)
{
return (
getModeratorEarningsRebalancedForCampaign(campaignAddress),
getContractorRebalancedLeftoverForCampaign(campaignAddress)
);
}
function getIfLeftoverForCampaignIsWithdrawn(
address campaignPlasma
)
public
view
returns (bool)
{
bool isWithdrawn = getBool(keccak256(_campaignPlasmaToLeftoverWithdrawnByContractor, campaignPlasma));
return isWithdrawn;
}
function getNonRebalancedReferrerRewards(
address campaignPlasma
)
public
view
returns (uint)
{
return getUint(keccak256(_campaignPlasma2ReferrerRewardsTotal, campaignPlasma));
}
/**
* @notice Function to get balance of stable coins on this contract
* @param stableCoinsAddresses is the array of stable coins addresses we want to fetch
* balances for
*/
function getBalanceOfStableCoinsOnContract(
address [] stableCoinsAddresses
)
public
view
returns (uint[])
{
uint len = stableCoinsAddresses.length;
uint [] memory balances = new uint[](len);
uint i;
for(i = 0; i < len; i++) {
balances[i] = IERC20(stableCoinsAddresses[i]).balanceOf(address(this));
}
return balances;
}
/**
* @notice Function to check amount of stable coins used to func ppc campaign
* @param campaignPlasma is campaign plasma address
*/
function getAmountOfStableCoinsUsedToFundCampaign(
address campaignPlasma
)
public
view
returns (uint)
{
return getUint(keccak256(_campaignPlasma2amountOfStableCoins, campaignPlasma));
}
/**
* @notice Function to return bounty per conversion in 2KEY tokens
* @param campaignPlasma is plasma campaign of address requested
*/
function getBountyPerConversion2KEY(
address campaignPlasma
)
public
view
returns (uint)
{
return getUint(
keccak256(_campaignPlasma2bountyPerConversion2KEY, campaignPlasma)
);
}
/**
* @notice Function to check if campaign is budgeted directly with 2KEY
*/
function getIsCampaignBudgetedDirectlyWith2KEY(
address campaignPlasma
)
public
view
returns (bool)
{
return getBool(keccak256(_campaignPlasma2isBudgetedWith2KeyDirectly, campaignPlasma));
}
function getStableCoinAddressUsedToFundCampaign(
address campaignPlasma
)
public
view
returns (address)
{
return getAddress(keccak256(_campaignPlasma2StableCoinAddress, campaignPlasma));
}
/**
* @notice Function to return summary related to specific campaign
* @param campaignPlasma is plasma campaign of address
*/
function getCampaignSummary(
address campaignPlasma
)
public
view
returns (bytes)
{
return (
abi.encodePacked(
getInitialBountyForCampaign(campaignPlasma),
getBountyPerConversion2KEY(campaignPlasma),
getAmountOfStableCoinsUsedToFundCampaign(campaignPlasma),
getInitial2KEYRateForCampaign(campaignPlasma),
getContractorRebalancedLeftoverForCampaign(campaignPlasma),
getModeratorEarningsRebalancedForCampaign(campaignPlasma),
getRebalancingRatioForCampaign(campaignPlasma),
getNonRebalancedReferrerRewards(campaignPlasma),
getIfLeftoverForCampaignIsWithdrawn(campaignPlasma)
)
);
}
/**
* @notice Function to fetch inital params computed while adding inventory
* @param campaignPlasma is the plasma address of the campaign being requested
*/
function getInitialParamsForCampaign(
address campaignPlasma
)
public
view
returns (uint,uint,uint,bool,address)
{
return (
getInitialBountyForCampaign(campaignPlasma), // initial bounty for campaign
getBountyPerConversion2KEY(campaignPlasma), // bounty per conversion in 2KEY tokens
getInitial2KEYRateForCampaign(campaignPlasma), // rate at the moment of inventory adding
getIsCampaignBudgetedDirectlyWith2KEY(campaignPlasma), // Get if campaign is funded directly with 2KEY
getCampaignContractor(campaignPlasma) // get contractor of campaign
);
}
function getCampaignContractor(
address campaignAddress
)
public
view
returns (address)
{
return getAddress(keccak256(_campaignPlasma2contractor, campaignAddress));
}
/**
*
*/
function getRequiredBudget2KEY(
string fiatCurrency,
uint fiatBudgetAmount
)
public
view
returns (uint)
{
// GET 2KEY - USD rate
uint rate = IUpgradableExchange(getAddressFromTwoKeySingletonRegistry("TwoKeyUpgradableExchange")).sellRate2key();
// For now ignore fiat currency assuming it's USD always
return fiatBudgetAmount.mul(10 ** 18).div(rate);
}
function getFeePerCycleIdPerReferrer(
uint cycleId
)
public
view
returns (uint)
{
return getUint(keccak256(_feePerCycleIdPerReferrer, cycleId));
}
}
|
Function to get how much is distributed in cycle cycleId is the ID of that cycle/
|
function getTotalDistributedInCycle(
uint cycleId
)
public
view
returns (uint)
{
return getUint(keccak256(_distributionCycleToTotalDistributed, cycleId));
}
| 13,574,471
|
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title REP2 Token
* @dev REP2 Mintable Token with migration from legacy contract
*/
contract MPKToken is StandardToken {
string public constant name = "ๅพฎ้้พ";
string public constant symbol = "MPK";
uint256 public constant decimals = 18;
/**
* @dev Creates a new MPKToken instance
*/
function MPKToken()public {
totalSupply = 5 * (10 ** 7) * (10 ** 18);
balances[0xc47fe4093c90b4480f8c84928d262207Fc0aDeEB] = totalSupply;
emit Transfer(0, 0xe3Fd212163D4252D4d82cfda607010016ec7F31C, totalSupply );
}
}
|
Creates a new MPKToken instance/
|
function MPKToken()public {
totalSupply = 5 * (10 ** 7) * (10 ** 18);
balances[0xc47fe4093c90b4480f8c84928d262207Fc0aDeEB] = totalSupply;
emit Transfer(0, 0xe3Fd212163D4252D4d82cfda607010016ec7F31C, totalSupply );
}
| 1,718,957
|
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
contract TransferTrade {
struct TicketInfo {
string concertName;
string day; // ๋์ค์ ํ์
๋ค์ ์๊ฐํ๊ธฐ
string time; // ๋์ค์ ํ์
๋ค์ ์๊ฐํ๊ธฐ
Seat seat;
uint32 ticketPrice;
bool isTransferred;
address payable owner;
}
struct Seat {
string typeOfSeat;
uint32 seatNumber;
}
// ๋ํดํธ ํฐ์ผ ์์ฑ
Seat public defaultSeat = Seat("VIP", 30);
TicketInfo defaultTicket = TicketInfo("์ค๋ง์ด๊ฑธ", "2021-06-18", "18:00", defaultSeat, 100000, false, 0x1c049AC608CB6B8B748Ed0449B9d592b9CDe2314);
// ์์
uint256 constant internal TICKET_PRICE = 5 * 10 ** 15;
// ๋ณ์
address payable public transferee;
// ์ด๋ฒคํธ
event GetMyTransferringTicket(string concertName, string day, string time, string typeOfSeat, uint32 seatNumber, uint32 ticketPrice);
event GetMyTicket(string concertName, string day, string time, string typeOfSeat, uint32 seatNumber, uint32 ticketPrice);
event FinishPay(address transferee);
event GetDefaultTicket(string concertName, string day, string time, Seat defaultSeat, uint32 ticketPrice, address owner);
// ์์ฑ์
constructor() public payable {
transferee = msg.sender;
}
/**
* @dev DefaultTicket ๊ฐ์ ธ์ค๊ธฐ
*/
function getDefaultTicket() public {
emit GetDefaultTicket(defaultTicket.concertName, defaultTicket.day, defaultTicket.time, defaultTicket.seat, defaultTicket.ticketPrice, defaultTicket.owner);
}
/**
* @dev ์๋ ์ ์ฒญ ์ฒ๋ฆฌ ํจ์
*/
function transferApplication() public payable returns (bool){
// alreadyTransferringTicket์ ํ์ธ, ์์๋ก ๋ฐ๋ชจ๋ฅผ ์ํด require๋ง์ ์ฌ์ฉํ์ฌ ๊ฑฐ๋๊ฐ ์งํ์ค์ธ์ง ํ์ธํ๋ค.
require(defaultTicket.isTransferred == false, "Already ticket is transferred");
// pay
pay();
// changeTicketInfo
changeTicketInfo();
return true;
}
/**
* @dev ์ด๋ฏธ ๊ฑฐ๋์ค์ธ ํฐ์ผ์ธ ๊ฒฝ์ฐ
*/
function alreadyTransferringTicket() internal returns (bool result){
return false;
}
/**
* @dev ์์์ธ์ ๊ณ์ข์์ ํฐ์ผ ๊ฐ๊ฒฉ์ ๋ฐ์ ์๋์ธ์๊ฒ ์ก๊ธํ๋ค.
*/
function pay() public payable {
// ํ์ฌ ๊ฐ๋์๋ฅผ ์คํ์ค์ด ์๋๋ผ์ ticket info์ owner ์ ๋ณด๊ฐ ์์ด์ ์ฃผ์์ฒ๋ฆฌํจ
require(msg.value == TICKET_PRICE, "Not enough ETH");
defaultTicket.isTransferred = true; // ์ง๋ถ์ ์งํํ ์ ์๋ ์ํ์ด๊ธฐ ๋๋ฌธ์, ์๋๊ฑฐ๋ ์งํ ์ค์์ ํ์ํ๋ค.
defaultTicket.owner.transfer(TICKET_PRICE);
emit FinishPay(transferee);
}
/**
* @dev ์๋๊ฑฐ๋๊ฐ ๋๋ ํฐ์ผ์ ์ ๋ณด๋ฅผ ์์ ํ๋ค.
*/
function changeTicketInfo() public returns (address) {
// owner change
// ํ์ฌ ๊ฐ๋์๋ฅผ ์คํ์ค์ด ์๋๋ผ์ ticket info์ owner ์ ๋ณด๊ฐ ์์ด์ ์ฃผ์์ฒ๋ฆฌํจ
defaultTicket.owner = transferee;
return defaultTicket.owner;
}
/**
* @dev ๋ง์ดํ์ด์ง์์ ์งํ์ค์ธ ์๋๊ฑฐ๋ ํฐ์ผ์ ๋ณด์ฌ์ค๋ค.
* (์ง๋ถ์ด ๋๋์ผ ๊ฑฐ๋ ์ฑ์ฌ๊ฐ ๋๋ ๊ฒ์ด๊ธฐ ๋๋ฌธ์, ์ด๋ ์๋์ธ์๊ฒ๋ง ๋ณด์ฌ์ฃผ๋ฉด ๋๋ค.)
* @return ์ฝ์ํธ ์ด๋ฆ์ ๋ฐํํ๋ค. (์ด๋ ํ
์คํธ๋ฅผ ์ํ ์ฉ๋์ด๋ค.)
*/
function getMyTransferringTicket() public returns (string memory){
require(defaultTicket.isTransferred == false, "Ticket trade is completed.");
emit GetMyTransferringTicket(defaultTicket.concertName, defaultTicket.day, defaultTicket.time, defaultTicket.seat.typeOfSeat, defaultTicket.seat.seatNumber, defaultTicket.ticketPrice);
string memory name = defaultTicket.concertName;
return name;
}
/**
* @dev ๋ง์ดํ์ด์ง์์ ์์ ํ๊ณ ์๋ ํฐ์ผ์ ๋ณด์ฌ์ค๋ค.
* @return ์ฝ์ํธ ์ด๋ฆ๊ณผ ํ์ฌ ํฐ์ผ ์์ ์ฃผ๋ฅผ ๋ฐํํ๋ค. (์ด๋ ํ
์คํธ๋ฅผ ์ํ ์ฉ๋์ด๋ค.)
*
*/
function getMyTicket() public returns (string memory, address){
require(msg.sender == defaultTicket.owner, "You aren't owner.. So it's impossible confirm.");
emit GetMyTicket(defaultTicket.concertName, defaultTicket.day, defaultTicket.time, defaultTicket.seat.typeOfSeat, defaultTicket.seat.seatNumber, defaultTicket.ticketPrice);
string memory name = defaultTicket.concertName;
address ownerAddress = defaultTicket.owner;
return (name, ownerAddress);
}
}
|
์๋๊ฑฐ๋๊ฐ ๋๋ ํฐ์ผ์ ์ ๋ณด๋ฅผ ์์ ํ๋ค./ owner change ํ์ฌ ๊ฐ๋์๋ฅผ ์คํ์ค์ด ์๋๋ผ์ ticket info์ owner ์ ๋ณด๊ฐ ์์ด์ ์ฃผ์์ฒ๋ฆฌํจ
|
function changeTicketInfo() public returns (address) {
defaultTicket.owner = transferee;
return defaultTicket.owner;
}
| 5,368,018
|
./full_match/1/0x2760712092BA61e67043fE04FF3c4f54cd045ca0/sources/contracts/vaults/Drops4626.sol
|
See {IERC4626-maxWithdraw}
|
function maxWithdraw(address owner) external view returns (uint256) {
return
_convertToAssets(balanceOf(owner), MathUpgradeable.Rounding.Down);
}
| 2,955,550
|
./full_match/5/0x5c946740441C12510a167B447B7dE565C20b9E3C/sources/contracts/token/GraphToken.sol
|
Approve token allowance by validating a message signed by the holder. _owner Address of the token holder _spender Address of the approved spender _value Amount of tokens to approve the spender _deadline Expiration time of the signed permit _v Signature version _r Signature r value _s Signature s value/
|
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner], _deadline)
)
)
);
nonces[_owner] = nonces[_owner].add(1);
address recoveredAddress = ECDSA.recover(digest, abi.encodePacked(_r, _s, _v));
require(_owner == recoveredAddress, "GRT: invalid permit");
require(_deadline == 0 || block.timestamp <= _deadline, "GRT: expired permit");
_approve(_owner, _spender, _value);
}
| 7,036,677
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {Ownable} from "openzeppelin/contracts/access/Ownable.sol";
import {ConfigContract} from "./ConfigContract.sol";
import {BatcherContract, BatchConfig, TransactionType} from "./BatcherContract.sol";
import {DepositContract} from "./DepositContract.sol";
struct CipherExecutionReceipt {
bool executed;
address executor;
uint64 halfStep;
bytes32 cipherBatchHash;
bytes32 batchHash;
}
/// @title A contract that serves as the entry point of batch execution
/// @dev Batch execution is carried out in two separate steps: Execution of the encrypted portion,
/// followed by execution of the plaintext portion. Thus, progress is counted in half steps (0
/// and 1 for batch 0, 2 and 3 for batch 1, and so on).
contract ExecutorContract is Ownable {
/// @notice The event emitted after a batch execution half step has been carried out.
/// @param numExecutionHalfSteps The total number of finished execution half steps, including
/// the one responsible for emitting the event.
/// @param batchHash The hash of the executed batch (consisting of plaintext transactions).
event BatchExecuted(uint64 numExecutionHalfSteps, bytes32 batchHash);
/// @notice The event emitted after execution of the cipher portion of a batch has been skipped.
/// @param numExecutionHalfSteps The total number of finished execution half steps, including
/// this one.
event CipherExecutionSkipped(uint64 numExecutionHalfSteps);
event TransactionFailed(uint64 txIndex, bytes32 txHash, bytes data);
ConfigContract public configContract;
BatcherContract public batcherContract;
DepositContract public depositContract;
uint64 public numExecutionHalfSteps;
mapping(uint64 => CipherExecutionReceipt) public cipherExecutionReceipts;
constructor(
ConfigContract configContractAddress,
BatcherContract batcherContractAddress,
DepositContract depositContractAddress
) Ownable() {
configContract = configContractAddress;
batcherContract = batcherContractAddress;
depositContract = depositContractAddress;
}
/// @notice Set the half step for accelerated recovery in case execution was neglected for some time.
/// @notice This function can only be called by the owner and only if the execution timeout has passed.
/// @notice The new half step must be greater than the current one, but cannot be in the future.
/// @param newHalfSteps The new value for numExecutionHalfSteps.
function setHalfSteps(uint64 newHalfSteps) public onlyOwner {
uint64 batchIndex = numExecutionHalfSteps / 2;
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
(, , uint64 executionTimeout) = configContract.batchBoundaryBlocks(
configIndex,
batchIndex
);
// check that execution timeout has passed
require(
block.number >= executionTimeout,
"ExecutorContract: execution timeout not passed yet"
);
// check that new half step is after current one
require(
newHalfSteps > numExecutionHalfSteps,
"ExecutorContract: new half steps not greater than current value"
);
// check that new half step is not in the future
uint64 newBatchIndex = newHalfSteps / 2;
uint64 newConfigIndex = configContract.configIndexForBatchIndex(
newBatchIndex
);
(, uint64 batchEndBlock, ) = configContract.batchBoundaryBlocks(
newConfigIndex,
newBatchIndex
);
require(
batchEndBlock < block.number,
"ExecutorContract: new half steps value is in the future"
);
numExecutionHalfSteps = newHalfSteps;
}
/// @notice Execute the cipher portion of a batch.
/// @param batchIndex The index of the batch
/// @param cipherBatchHash The hash of the batch (consisting of encrypted transactions)
/// @param transactions The sequence of (decrypted) transactions to execute.
/// @param keyperIndex The index of the keyper calling the function.
/// @notice Execution is only performed if `cipherBatchHash` matches the hash in the batcher
/// contract and the batch is active and completed.
function executeCipherBatch(
uint64 batchIndex,
bytes32 cipherBatchHash,
bytes[] calldata transactions,
uint64 keyperIndex
) public {
require(
numExecutionHalfSteps / 2 == batchIndex,
"ExecutorContract: unexpected batch index"
);
// Check that it's a cipher batch turn
require(
numExecutionHalfSteps % 2 == 0,
"ExecutorContract: unexpected half step"
);
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
address targetAddress = configContract.configTargetAddress(configIndex);
bytes4 targetFunctionSelector = configContract
.configTargetFunctionSelector(configIndex);
uint64 transactionGasLimit = configContract.configTransactionGasLimit(
configIndex
);
// Check that batching is active
require(
configContract.batchingActive(configIndex),
"ExecutorContract: config is inactive"
);
(, uint64 end, uint64 executionTimeout) = configContract
.batchBoundaryBlocks(configIndex, batchIndex);
// skip cipher execution if we reached the execution timeout.
if (block.number >= executionTimeout) {
numExecutionHalfSteps++;
emit CipherExecutionSkipped(numExecutionHalfSteps);
return;
}
require(
block.number >= end,
"ExecutorContract: batch is not closed yet"
);
// Check that caller is keyper
uint64 numKeypers = configContract.configNumKeypers(configIndex);
require(
keyperIndex < numKeypers,
"ExecutorContract: keyper index out of bounds"
);
address keyperAtIndex = configContract.configKeypers(
configIndex,
keyperIndex
);
require(
msg.sender == keyperAtIndex,
"ExecutorContract: sender is not specified keyper"
);
// Check that keyper is not slashed
require(
!depositContract.isSlashed(msg.sender),
"ExecutorContract: keyper is slashed"
);
// Check the cipher batch hash is correct
require(
cipherBatchHash ==
batcherContract.batchHashes(batchIndex, TransactionType.Cipher),
"ExecutorContract: incorrect cipher batch hash"
);
// If the cipher hash is zero, make sure the list of
// transactions is empty. Please note that we may have a
// non-zero cipher hash and still have an empty list of
// transactions, e.g. when a nondecryptable transaction has
// been added by a user
require(
(cipherBatchHash != bytes32(0) || transactions.length == 0),
"ExecutorContract: transactions should be empty if cipherBatchHash is zero"
);
// Execute the batch
bytes32 batchHash = executeTransactions(
targetAddress,
targetFunctionSelector,
transactionGasLimit,
transactions
);
cipherExecutionReceipts[
numExecutionHalfSteps
] = CipherExecutionReceipt({
executed: true,
executor: msg.sender,
halfStep: numExecutionHalfSteps,
cipherBatchHash: cipherBatchHash,
batchHash: batchHash
});
numExecutionHalfSteps++;
emit BatchExecuted(numExecutionHalfSteps, batchHash);
}
function skipEmptyOrTimedOutBatches(uint64 maxBatches) public {
uint64 halfSteps = numExecutionHalfSteps;
uint64 batchIndex = halfSteps / 2;
while (maxBatches > 0) {
if (halfSteps % 2 == 0) {
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
if (!configContract.batchingActive(configIndex)) {
break;
}
(, uint64 end, uint64 executionTimeout) = configContract
.batchBoundaryBlocks(configIndex, batchIndex);
if (block.number < end) {
// Users may still submit transactions
break;
}
if (
block.number < executionTimeout &&
batcherContract.batchHashes(
batchIndex,
TransactionType.Cipher
) !=
bytes32(0)
) {
break;
}
halfSteps += 1;
emit CipherExecutionSkipped(halfSteps);
}
if (
batcherContract.batchHashes(
batchIndex,
TransactionType.Plain
) != bytes32(0)
) {
break;
}
halfSteps += 1;
batchIndex += 1;
emit BatchExecuted(halfSteps, bytes32(0));
maxBatches -= 1;
}
numExecutionHalfSteps = halfSteps;
}
/// @notice Skip execution of the cipher portion of a batch.
/// @notice This is only possible if successful execution has not been carried out in time
/// (according to the execution timeout defined in the config)
function skipCipherExecution(uint64 batchIndex) external {
require(
numExecutionHalfSteps / 2 == batchIndex,
"ExecutorContract: unexpected batch index"
);
require(
numExecutionHalfSteps % 2 == 0,
"ExecutorContract: unexpected half step"
);
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
require(
configContract.batchingActive(configIndex),
"ExecutorContract: config is inactive"
);
(, , uint64 executionTimeout) = configContract.batchBoundaryBlocks(
configIndex,
batchIndex
);
require(
block.number >= executionTimeout,
"ExecutorContract: execution timeout not reached yet"
);
numExecutionHalfSteps++;
emit CipherExecutionSkipped(numExecutionHalfSteps);
}
/// @notice Execute the plaintext portion of a batch.
/// @param batchIndex The index of the batch
/// @param transactions The array of plaintext transactions in the batch.
/// @notice This is a trustless operation since `transactions` will be checked against the
/// (plaintext) batch hash from the batcher contract.
function executePlainBatch(uint64 batchIndex, bytes[] calldata transactions)
external
{
require(
numExecutionHalfSteps / 2 == batchIndex,
"ExecutorContract: unexpected batch index"
);
require(
numExecutionHalfSteps % 2 == 1,
"ExecutorContract: unexpected half step"
);
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
address targetAddress = configContract.configTargetAddress(configIndex);
bytes4 targetFunctionSelector = configContract
.configTargetFunctionSelector(configIndex);
uint64 transactionGasLimit = configContract.configTransactionGasLimit(
configIndex
);
// Since the cipher part of the batch has already been executed or skipped and the
// config cannot be changed anymore (since the batching period is over), the following
// checks remain true.
assert(configContract.batchingActive(configIndex));
(, uint64 end, ) = configContract.batchBoundaryBlocks(
configIndex,
batchIndex
);
assert(block.number >= end);
bytes32 batchHash = executeTransactions(
targetAddress,
targetFunctionSelector,
transactionGasLimit,
transactions
);
require(
batchHash ==
batcherContract.batchHashes(batchIndex, TransactionType.Plain),
"ExecutorContract: batch hash does not match"
);
numExecutionHalfSteps++;
emit BatchExecuted(numExecutionHalfSteps, batchHash);
}
function executeTransactions(
address targetAddress,
bytes4 targetFunctionSelector,
uint64 gasLimit,
bytes[] calldata transactions
) private returns (bytes32) {
bytes32 batchHash;
for (uint64 i = 0; i < transactions.length; i++) {
bytes memory callData = abi.encodeWithSelector(
targetFunctionSelector,
transactions[i]
);
// call target function, ignoring any errors
(bool success, bytes memory returnData) = targetAddress.call{
gas: gasLimit
}(callData);
if (!success) {
emit TransactionFailed({
txIndex: i,
txHash: keccak256(transactions[i]),
data: returnData
});
}
batchHash = keccak256(abi.encodePacked(transactions[i], batchHash));
}
return batchHash;
}
function getReceipt(uint64 halfStep)
public
view
returns (CipherExecutionReceipt memory)
{
return cipherExecutionReceipts[halfStep];
}
}
|
Execute the cipher portion of a batch. batchIndex The index of the batch cipherBatchHash The hash of the batch (consisting of encrypted transactions) transactions The sequence of (decrypted) transactions to execute. keyperIndex The index of the keyper calling the function. Execution is only performed if `cipherBatchHash` matches the hash in the batcher contract and the batch is active and completed. Check that it's a cipher batch turn Check that batching is active skip cipher execution if we reached the execution timeout.
|
function executeCipherBatch(
uint64 batchIndex,
bytes32 cipherBatchHash,
bytes[] calldata transactions,
uint64 keyperIndex
) public {
require(
numExecutionHalfSteps / 2 == batchIndex,
"ExecutorContract: unexpected batch index"
);
require(
numExecutionHalfSteps % 2 == 0,
"ExecutorContract: unexpected half step"
);
uint64 configIndex = configContract.configIndexForBatchIndex(
batchIndex
);
address targetAddress = configContract.configTargetAddress(configIndex);
bytes4 targetFunctionSelector = configContract
.configTargetFunctionSelector(configIndex);
uint64 transactionGasLimit = configContract.configTransactionGasLimit(
configIndex
);
require(
configContract.batchingActive(configIndex),
"ExecutorContract: config is inactive"
);
(, uint64 end, uint64 executionTimeout) = configContract
.batchBoundaryBlocks(configIndex, batchIndex);
if (block.number >= executionTimeout) {
numExecutionHalfSteps++;
emit CipherExecutionSkipped(numExecutionHalfSteps);
return;
}
require(
block.number >= end,
"ExecutorContract: batch is not closed yet"
);
require(
keyperIndex < numKeypers,
"ExecutorContract: keyper index out of bounds"
);
address keyperAtIndex = configContract.configKeypers(
configIndex,
keyperIndex
);
require(
msg.sender == keyperAtIndex,
"ExecutorContract: sender is not specified keyper"
);
!depositContract.isSlashed(msg.sender),
"ExecutorContract: keyper is slashed"
);
cipherBatchHash ==
batcherContract.batchHashes(batchIndex, TransactionType.Cipher),
"ExecutorContract: incorrect cipher batch hash"
);
(cipherBatchHash != bytes32(0) || transactions.length == 0),
"ExecutorContract: transactions should be empty if cipherBatchHash is zero"
);
targetAddress,
targetFunctionSelector,
transactionGasLimit,
transactions
);
cipherExecutionReceipts[
numExecutionHalfSteps
] = CipherExecutionReceipt({
executed: true,
executor: msg.sender,
halfStep: numExecutionHalfSteps,
cipherBatchHash: cipherBatchHash,
batchHash: batchHash
});
numExecutionHalfSteps++;
emit BatchExecuted(numExecutionHalfSteps, batchHash);
}
| 12,849,434
|
/**
*Submitted for verification at Etherscan.io on 2021-03-11
*/
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.8.0;
contract ERC20Interface {
/// @return supply total amount of tokens
function totalSupply() public virtual view returns (uint256 supply) {}
/// @param tokenOwner The address from which the balance will be retrieved
/// @return balance The balance
function balanceOf(address tokenOwner) public virtual 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 success Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public virtual 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 success Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public virtual 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 success Whether the approval was successful or not
function approve(address _spender, uint256 _value) public virtual returns (bool success) {}
/// @param tokenOwner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return remaining Amount of remaining tokens allowed to spent
function allowance(address tokenOwner, address _spender) public virtual view returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is ERC20Interface {
uint256 public _totalSupply;
mapping (address => uint256) balances;
//[tokenOwner][spender] = value
//tokenOwner allows the spender to spend *value* of tokenOwner money
mapping (address => mapping (address => uint256)) allowed;
function transfer(address _to, uint256 _value) public override returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) public override returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address tokenOwner) public view override returns (uint256 balance) {
return balances[tokenOwner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address tokenOwner, address _spender) public view override returns (uint256 remaining) {
return allowed[tokenOwner][_spender];
}
function totalSupply() public view override returns (uint) {
return _totalSupply - balances[address(0)];
}
}
contract MobiToken is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H0.1';
constructor() {
_totalSupply = 410000000; // Update total supply
balances[msg.sender] = _totalSupply; // Give the creator all initial tokens
name = "Mobi Coin"; // Set the name for display purposes
decimals = 2; // Amount of decimals for display purposes
symbol = "MOBI"; // Set the symbol for display purposes
}
}
|
send `_value` token to `_to` from `_from` on the condition it is approved by `_from` _from The address of the sender _to The address of the recipient _value The amount of token to be transferred return success Whether the transfer was successful or not
|
function transferFrom(address _from, address _to, uint256 _value) public virtual returns (bool success) {}
| 8,028,514
|
./full_match/11155111/0x7AC9EADa77282c5228f53D4f4338e5f214B30aCf/sources/contracts/CrowdFunding.sol
|
Campaign storage campaign = campaigns[numberOfCampaigns];
|
function isFundSuccess() public view returns(bool) {
if(address(this).balance >= campaign1.target || campaign1.fundsWithdrawn) {
return true;
return false;
}
}
| 3,801,870
|
./full_match/80001/0xe2A518399f115EB2bd590C8f24F10f5Bd38d1cE7/sources/project_/contracts/token/Token.sol
|
See {ERC20-_burn}./
|
function _burn(address _userAddress, uint256 _amount) internal virtual {
require(_userAddress != address(0), 'ERC20: burn from the zero address');
_beforeTokenTransfer(_userAddress, address(0), _amount);
_balances[_userAddress] = _balances[_userAddress] - _amount;
_totalSupply = _totalSupply - _amount;
emit Transfer(_userAddress, address(0), _amount);
}
| 5,693,497
|
// EverOwn Wrapper contract exmaple
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(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;
}
}
// If interfaces are needed add them here
// IERC20/IBEP20 standard interface.
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address _owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* Any contract methods that are required
*/
interface IMyContract {
// Any other/different contract wrapper methods if ownership transfer is not via transferOwnership
function transferOwnership(address payable _address) external;
}
contract Ownable is Context {
address private _owner;
address private _buybackOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function transferOwnership(address newOwner) external virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function owner() public view returns (address) {
return _owner;
}
}
// *** Rename this to your proxy wrapper contract
contract MyContractOwn is Ownable {
// *** Rename to be an ownership proxy for your token e.g. xxxxOWN
string private _name = "MyContractOwn";
string private _symbol = "MyContracOWN";
IMyContract public token;
constructor (address _token) {
token = IMyContract(payable(_token));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
// *** Releasing the ownership from the wrapper contract back to owner
function releaseOwnership() public onlyOwner {
// ****
// If your contract uses a different ownership technique and that's why you are wrapping
// change the body of this function to match that
// ***
token.transferOwnership(_msgSender());
}
// Function to release ETH trapped in wrapper, can be released when ownership returned
function releaseTrappedETH(address payable toAddress) external onlyOwner {
require(toAddress != address(0), "toAddress can not be a zero address");
toAddress.transfer(address(this).balance);
}
// Function to release tokens trapped in wrapper, can be released when ownership returned
function releaseTrappedTokens(address tokenAddress, address toAddress) external onlyOwner {
require(tokenAddress != address(0), "tokenAddress can not be a zero address");
require(toAddress != address(0), "toAddress can not be a zero address");
require(IERC20(tokenAddress).balanceOf(address(this)) > 0, "Balance is zero");
IERC20(tokenAddress).transfer(toAddress, IERC20(tokenAddress).balanceOf(address(this)));
}
// To recieve ETH
receive() external payable {}
// Fallback function to receive ETH when msg.data is not empty
fallback() external payable {}
}
|
Function to release tokens trapped in wrapper, can be released when ownership returned
|
function releaseTrappedTokens(address tokenAddress, address toAddress) external onlyOwner {
require(tokenAddress != address(0), "tokenAddress can not be a zero address");
require(toAddress != address(0), "toAddress can not be a zero address");
require(IERC20(tokenAddress).balanceOf(address(this)) > 0, "Balance is zero");
IERC20(tokenAddress).transfer(toAddress, IERC20(tokenAddress).balanceOf(address(this)));
}
| 6,414,693
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.