file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
./partial_match/1/0xfB531Ce4963CbD652167e1561e99a95406Ec857D/sources/LOL.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("LOL", "LOL") {
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 = 20;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 60;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 _earlySellLiquidityFee = 0;
uint256 _earlySellMarketingFee = 0;
uint256 totalSupply = 1 * 1e8 * 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;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 2,673,808
|
// File: contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// File: contracts/interfaces/IOneSwapToken.sol
pragma solidity 0.6.12;
interface IOneSwapBlackList {
event OwnerChanged(address);
event AddedBlackLists(address[]);
event RemovedBlackLists(address[]);
function owner()external view returns (address);
function newOwner()external view returns (address);
function isBlackListed(address)external view returns (bool);
function changeOwner(address ownerToSet) external;
function updateOwner() external;
function addBlackLists(address[] calldata accounts)external;
function removeBlackLists(address[] calldata accounts)external;
}
interface IOneSwapToken is IERC20, IOneSwapBlackList{
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function multiTransfer(uint256[] calldata mixedAddrVal) external returns (bool);
}
// File: contracts/interfaces/IOneSwapGov.sol
pragma solidity 0.6.12;
interface IOneSwapGov {
event NewFundsProposal (uint64 proposalID, string title, string desc, string url, uint32 deadline, address beneficiary, uint256 amount);
event NewParamProposal (uint64 proposalID, string title, string desc, string url, uint32 deadline, address factory, uint32 feeBPS);
event NewUpgradeProposal(uint64 proposalID, string title, string desc, string url, uint32 deadline, address factory, address pairLogic);
event NewTextProposal (uint64 proposalID, string title, string desc, string url, uint32 deadline);
event NewVote(uint64 proposalID, address voter, uint8 opinion, uint112 voteAmt);
event AddVote(uint64 proposalID, address voter, uint8 opinion, uint112 voteAmt);
event Revote (uint64 proposalID, address voter, uint8 opinion, uint112 voteAmt);
event TallyResult(uint64 proposalID, bool pass);
function ones() external pure returns (address);
function proposalInfo() external view returns (
uint24 id, address proposer, uint8 _type, uint32 deadline, address addr, uint256 value,
uint112 totalYes, uint112 totalNo, uint112 totalDeposit);
function voterInfo(address voter) external view returns (
uint24 votedProposalID, uint8 votedOpinion, uint112 votedAmt, uint112 depositedAmt);
function submitFundsProposal (string calldata title, string calldata desc, string calldata url, address beneficiary, uint256 fundsAmt, uint112 voteAmt) external;
function submitParamProposal (string calldata title, string calldata desc, string calldata url, address factory, uint32 feeBPS, uint112 voteAmt) external;
function submitUpgradeProposal(string calldata title, string calldata desc, string calldata url, address factory, address pairLogic, uint112 voteAmt) external;
function submitTextProposal (string calldata title, string calldata desc, string calldata url, uint112 voteAmt) external;
function vote(uint8 opinion, uint112 voteAmt) external;
function tally() external;
function withdrawOnes(uint112 amt) external;
}
// File: contracts/interfaces/IOneSwapFactory.sol
pragma solidity 0.6.12;
interface IOneSwapFactory {
event PairCreated(address indexed pair, address stock, address money, bool isOnlySwap);
function createPair(address stock, address money, bool isOnlySwap) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setFeeBPS(uint32 bps) external;
function setPairLogic(address implLogic) external;
function allPairsLength() external view returns (uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function feeBPS() external view returns (uint32);
function pairLogic() external returns (address);
function getTokensFromPair(address pair) external view returns (address stock, address money);
function tokensToPair(address stock, address money, bool isOnlySwap) external view returns (address pair);
}
// File: contracts/OneSwapGov.sol
pragma solidity 0.6.12;
contract OneSwapGov is IOneSwapGov {
struct VoterInfo {
uint24 votedProposal;
uint8 votedOpinion;
uint112 votedAmt; // enouth to store ONES
uint112 depositedAmt; // enouth to store ONES
}
uint8 private constant _PROPOSAL_TYPE_FUNDS = 1; // ask for funds
uint8 private constant _PROPOSAL_TYPE_PARAM = 2; // change factory.feeBPS
uint8 private constant _PROPOSAL_TYPE_UPGRADE = 3; // change factory.pairLogic
uint8 private constant _PROPOSAL_TYPE_TEXT = 4; // pure text proposal
uint8 private constant _YES = 1;
uint8 private constant _NO = 2;
uint32 private constant _MIN_FEE_BPS = 0;
uint32 private constant _MAX_FEE_BPS = 50;
uint256 private constant _MAX_FUNDS_REQUEST = 5000000; // 5000000 ONES
uint256 private constant _FAILED_PROPOSAL_COST = 1000; // 1000 ONES
uint256 private constant _SUBMIT_ONES_PERCENT = 1; // 1%
uint256 private constant _VOTE_PERIOD = 3 days;
uint256 private constant _TEXT_PROPOSAL_INTERVAL = 1 days;
address public immutable override ones;
uint256 private immutable _maxFundsRequest; // 5000000 ONES
uint256 private immutable _failedProposalCost; // 1000 ONES
uint24 private _proposalID;
uint8 private _proposalType; // FUNDS | PARAM | UPGRADE | TEXT
uint32 private _deadline; // unix timestamp | same | same | same
address private _addr; // beneficiary addr | factory addr | factory addr | not used
uint256 private _value; // amount of funds | feeBPS | pair logic address | not used
address private _proposer;
uint112 private _totalYes;
uint112 private _totalNo;
uint112 private _totalDeposit;
mapping (address => VoterInfo) private _voters;
constructor(address _ones) public {
ones = _ones;
uint256 onesDec = IERC20(_ones).decimals();
_maxFundsRequest = _MAX_FUNDS_REQUEST * (10 ** onesDec);
_failedProposalCost = _FAILED_PROPOSAL_COST * (10 ** onesDec);
}
function proposalInfo() external view override returns (
uint24 id, address proposer, uint8 _type, uint32 deadline, address addr, uint256 value,
uint112 totalYes, uint112 totalNo, uint112 totalDeposit) {
id = _proposalID;
proposer = _proposer;
_type = _proposalType;
deadline = _deadline;
value = _value;
addr = _addr;
totalYes = _totalYes;
totalNo = _totalNo;
totalDeposit = _totalDeposit;
}
function voterInfo(address voter) external view override returns (
uint24 votedProposalID, uint8 votedOpinion, uint112 votedAmt, uint112 depositedAmt) {
VoterInfo memory info = _voters[voter];
votedProposalID = info.votedProposal;
votedOpinion = info.votedOpinion;
votedAmt = info.votedAmt;
depositedAmt = info.depositedAmt;
}
// submit new proposals
function submitFundsProposal(string calldata title, string calldata desc, string calldata url,
address beneficiary, uint256 fundsAmt, uint112 voteAmt) external override {
if (fundsAmt > 0) {
require(fundsAmt <= _maxFundsRequest, "OneSwapGov: ASK_TOO_MANY_FUNDS");
uint256 govOnes = IERC20(ones).balanceOf(address(this));
uint256 availableOnes = govOnes - _totalDeposit;
require(govOnes > _totalDeposit && availableOnes >= fundsAmt,
"OneSwapGov: INSUFFICIENT_FUNDS");
}
_newProposal(_PROPOSAL_TYPE_FUNDS, beneficiary, fundsAmt, voteAmt);
emit NewFundsProposal(_proposalID, title, desc, url, _deadline, beneficiary, fundsAmt);
_vote(_YES, voteAmt);
}
function submitParamProposal(string calldata title, string calldata desc, string calldata url,
address factory, uint32 feeBPS, uint112 voteAmt) external override {
require(feeBPS >= _MIN_FEE_BPS && feeBPS <= _MAX_FEE_BPS, "OneSwapGov: INVALID_FEE_BPS");
_newProposal(_PROPOSAL_TYPE_PARAM, factory, feeBPS, voteAmt);
emit NewParamProposal(_proposalID, title, desc, url, _deadline, factory, feeBPS);
_vote(_YES, voteAmt);
}
function submitUpgradeProposal(string calldata title, string calldata desc, string calldata url,
address factory, address pairLogic, uint112 voteAmt) external override {
require(pairLogic != address(0), "OneSwapGov: INVALID_PAIR_LOGIC");
_newProposal(_PROPOSAL_TYPE_UPGRADE, factory, uint256(pairLogic), voteAmt);
emit NewUpgradeProposal(_proposalID, title, desc, url, _deadline, factory, pairLogic);
_vote(_YES, voteAmt);
}
function submitTextProposal(string calldata title, string calldata desc, string calldata url,
uint112 voteAmt) external override {
// solhint-disable-next-line not-rely-on-time
require(uint256(_deadline) + _TEXT_PROPOSAL_INTERVAL < block.timestamp,
"OneSwapGov: COOLING_DOWN");
_newProposal(_PROPOSAL_TYPE_TEXT, address(0), 0, voteAmt);
emit NewTextProposal(_proposalID, title, desc, url, _deadline);
_vote(_YES, voteAmt);
}
function _newProposal(uint8 _type, address addr, uint256 value, uint112 voteAmt) private {
require(_type >= _PROPOSAL_TYPE_FUNDS && _type <= _PROPOSAL_TYPE_TEXT,
"OneSwapGov: INVALID_PROPOSAL_TYPE");
require(_type == _PROPOSAL_TYPE_TEXT || msg.sender == IOneSwapToken(ones).owner(),
"OneSwapGov: NOT_ONES_OWNER");
require(_proposalType == 0, "OneSwapGov: LAST_PROPOSAL_NOT_FINISHED");
uint256 totalOnes = IERC20(ones).totalSupply();
uint256 thresOnes = (totalOnes/100) * _SUBMIT_ONES_PERCENT;
require(voteAmt >= thresOnes, "OneSwapGov: VOTE_AMOUNT_TOO_LESS");
_proposalID++;
_proposalType = _type;
_proposer = msg.sender;
// solhint-disable-next-line not-rely-on-time
_deadline = uint32(block.timestamp + _VOTE_PERIOD);
_value = value;
_addr = addr;
_totalYes = 0;
_totalNo = 0;
}
function vote(uint8 opinion, uint112 voteAmt) external override {
require(_proposalType > 0, "OneSwapGov: NO_PROPOSAL");
// solhint-disable-next-line not-rely-on-time
require(uint256(_deadline) > block.timestamp, "OneSwapGov: DEADLINE_REACHED");
_vote(opinion, voteAmt);
}
function _vote(uint8 opinion, uint112 addedVoteAmt) private {
require(_YES <= opinion && opinion <= _NO, "OneSwapGov: INVALID_OPINION");
require(addedVoteAmt > 0, "OneSwapGov: ZERO_VOTE_AMOUNT");
(uint24 currProposalID, uint24 votedProposalID,
uint8 votedOpinion, uint112 votedAmt, uint112 depositedAmt) = _getVoterInfo();
// cancel previous votes if opinion changed
bool isRevote = false;
if ((votedProposalID == currProposalID) && (votedOpinion != opinion)) {
if (votedOpinion == _YES) {
assert(_totalYes >= votedAmt);
_totalYes -= votedAmt;
} else {
assert(_totalNo >= votedAmt);
_totalNo -= votedAmt;
}
votedAmt = 0;
isRevote = true;
}
// need to deposit more ONES?
assert(depositedAmt >= votedAmt);
if (addedVoteAmt > depositedAmt - votedAmt) {
uint112 moreDeposit = addedVoteAmt - (depositedAmt - votedAmt);
depositedAmt += moreDeposit;
_totalDeposit += moreDeposit;
IERC20(ones).transferFrom(msg.sender, address(this), moreDeposit);
}
if (opinion == _YES) {
_totalYes += addedVoteAmt;
} else {
_totalNo += addedVoteAmt;
}
votedAmt += addedVoteAmt;
_setVoterInfo(currProposalID, opinion, votedAmt, depositedAmt);
if (isRevote) {
emit Revote(currProposalID, msg.sender, opinion, addedVoteAmt);
} else if (votedAmt > addedVoteAmt) {
emit AddVote(currProposalID, msg.sender, opinion, addedVoteAmt);
} else {
emit NewVote(currProposalID, msg.sender, opinion, addedVoteAmt);
}
}
function _getVoterInfo() private view returns (uint24 currProposalID,
uint24 votedProposalID, uint8 votedOpinion, uint112 votedAmt, uint112 depositedAmt) {
currProposalID = _proposalID;
VoterInfo memory voter = _voters[msg.sender];
depositedAmt = voter.depositedAmt;
if (voter.votedProposal == currProposalID) {
votedProposalID = currProposalID;
votedOpinion = voter.votedOpinion;
votedAmt = voter.votedAmt;
}
}
function _setVoterInfo(uint24 proposalID,
uint8 opinion, uint112 votedAmt, uint112 depositedAmt) private {
_voters[msg.sender] = VoterInfo({
votedProposal: proposalID,
votedOpinion : opinion,
votedAmt : votedAmt,
depositedAmt : depositedAmt
});
}
function tally() external override {
require(_proposalType > 0, "OneSwapGov: NO_PROPOSAL");
// solhint-disable-next-line not-rely-on-time
require(uint256(_deadline) <= block.timestamp, "OneSwapGov: STILL_VOTING");
bool ok = _totalYes > _totalNo;
uint8 _type = _proposalType;
uint256 val = _value;
address addr = _addr;
address proposer = _proposer;
_resetProposal();
if (ok) {
_execProposal(_type, addr, val);
} else {
_taxProposer(proposer);
}
emit TallyResult(_proposalID, ok);
}
function _resetProposal() private {
_proposalType = 0;
// _deadline = 0; // use _deadline to check _TEXT_PROPOSAL_INTERVAL
_value = 0;
_addr = address(0);
_proposer = address(0);
_totalYes = 0;
_totalNo = 0;
}
function _execProposal(uint8 _type, address addr, uint256 val) private {
if (_type == _PROPOSAL_TYPE_FUNDS) {
if (val > 0) {
IERC20(ones).transfer(addr, val);
}
} else if (_type == _PROPOSAL_TYPE_PARAM) {
IOneSwapFactory(addr).setFeeBPS(uint32(val));
} else if (_type == _PROPOSAL_TYPE_UPGRADE) {
IOneSwapFactory(addr).setPairLogic(address(val));
}
}
function _taxProposer(address proposerAddr) private {
// burn 1000 ONES of proposer
uint112 cost = uint112(_failedProposalCost);
VoterInfo memory proposerInfo = _voters[proposerAddr];
if (proposerInfo.depositedAmt < cost) { // unreachable!
cost = proposerInfo.depositedAmt;
}
_totalDeposit -= cost;
proposerInfo.depositedAmt -= cost;
_voters[proposerAddr] = proposerInfo;
IOneSwapToken(ones).burn(cost);
}
function withdrawOnes(uint112 amt) external override {
VoterInfo memory voter = _voters[msg.sender];
require(_proposalType == 0 || voter.votedProposal < _proposalID, "OneSwapGov: IN_VOTING");
require(amt > 0 && amt <= voter.depositedAmt, "OneSwapGov: INVALID_WITHDRAW_AMOUNT");
_totalDeposit -= amt;
voter.depositedAmt -= amt;
if (voter.depositedAmt == 0) {
delete _voters[msg.sender];
} else {
_voters[msg.sender] = voter;
}
IERC20(ones).transfer(msg.sender, amt);
}
}
|
solhint-disable-next-line not-rely-on-time
|
function _newProposal(uint8 _type, address addr, uint256 value, uint112 voteAmt) private {
require(_type >= _PROPOSAL_TYPE_FUNDS && _type <= _PROPOSAL_TYPE_TEXT,
"OneSwapGov: INVALID_PROPOSAL_TYPE");
require(_type == _PROPOSAL_TYPE_TEXT || msg.sender == IOneSwapToken(ones).owner(),
"OneSwapGov: NOT_ONES_OWNER");
require(_proposalType == 0, "OneSwapGov: LAST_PROPOSAL_NOT_FINISHED");
uint256 totalOnes = IERC20(ones).totalSupply();
uint256 thresOnes = (totalOnes/100) * _SUBMIT_ONES_PERCENT;
require(voteAmt >= thresOnes, "OneSwapGov: VOTE_AMOUNT_TOO_LESS");
_proposalID++;
_proposalType = _type;
_proposer = msg.sender;
_deadline = uint32(block.timestamp + _VOTE_PERIOD);
_value = value;
_addr = addr;
_totalYes = 0;
_totalNo = 0;
}
| 1,158,710
|
./full_match/4/0x1Ca18a09c59ee102070399D37bc3aEa54Fa102Cc/sources/browser/myERC20.sol
|
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./ SafeMath.sub will throw if there is not enough balance.
|
function transfer(address _to, uint256 _value) public override returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
| 12,432,392
|
./full_match/1/0xe5Ae0ca966DEaBA8472456c89c494Ba4A590478B/sources/contracts/BrewlabsFarm.sol
|
Brews has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
|
function updateEmissionRate(uint256 _rewardPerBlock) external onlyOwner {
massUpdatePools();
rewardPerBlock = _rewardPerBlock;
emit UpdateEmissionRate(msg.sender, _rewardPerBlock);
}
| 4,842,552
|
pragma solidity ^0.4.15;
/*Visit http://titscrypto.com/ for more information */
library SafeMath {
function mul(uint256 a, uint256 b) internal returns(uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns(uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
} else {
_;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns(uint256);
function transfer(address to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns(uint256);
function transferFrom(address from, address to, uint256 value);
function approve(address spender, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath
for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns(uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping(address => mapping(address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) revert();
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
event MintStarted();
event RefundRequest(uint256 sum,address adr,uint256 balance);
event CoinBuy(uint256 sum,address adr);
bool public mintingFinished = true;
bool public goalReached = false;
uint public mintingStartTime = 0;
uint public maxMintingTime = 30 days;
uint public mintingGoal = 500 ether;
address public titsTokenAuthor = 0x189891d02445D87e70d515fD2159416f023B0087;
/**
* @dev Fell fre to donate Author if You like what is presented here
*/
function donateAuthor() payable {
titsTokenAuthor.transfer(msg.value);
}
bool public alreadyMintedOnce = false;
modifier mintingClosed() {
if (mintingFinished == false || alreadyMintedOnce == false) revert();
_;
}
modifier IsMintingGoal() {
if (mintingFinished == false || alreadyMintedOnce == false || goalReached == false ) revert();
_;
}
modifier notMintedYet() {
if (alreadyMintedOnce == true) revert();
_;
}
function getNow() public returns(uint256){
return now;
}
/**
* @dev Premium for buying TITS at the begining of ICO
* @return bool True if no errors
*/
function fastBuyBonus() private returns(uint) {
uint period = getNow() - mintingStartTime;
if (period < 1 days) {
return 3500;
}
if (period < 2 days) {
return 3200;
}
if (period < 3 days) {
return 3000;
}
if (period < 7 days) {
return 2600;
}
if (period < 10 days) {
return 2400;
}
if (period < 12 days) {
return 2200;
}
if (period < 14 days) {
return 2000;
}
if (period < 17 days) {
return 1800;
}
if (period < 19 days) {
return 1600;
}
if (period < 21 days) {
return 1400;
}
if (period < 23 days) {
return 1200;
}
return 1000;
}
/**
* @dev Allows to buy shares
* @return bool True if no errors
*/
function buy() payable returns(bool) {
if (mintingFinished) {
revert();
}
uint _amount = 0;
_amount = msg.value * fastBuyBonus();
totalSupply = totalSupply.add(_amount);
CoinBuy(_amount,msg.sender);
balances[msg.sender] = balances[msg.sender].add(_amount);
balances[owner] = balances[owner].add(_amount / 85 * 15); //15% shares of owner
totalSupply = totalSupply.add(_amount / 85 * 15);
return true;
}
/**
* @dev Opens ICO (only owner)
* @return bool True if no errors
*/
function startMinting() onlyOwner notMintedYet returns(bool) {
mintingStartTime = getNow();
alreadyMintedOnce = true;
mintingFinished = false;
MintStarted();
return true;
}
/**
* @dev Closes ICO - anyone can invoke if invoked to soon, takes no actions
* @return bool True if no errors
*/
function finishMinting() returns(bool) {
if (mintingFinished == false) {
if (getNow() - mintingStartTime > maxMintingTime) {
mintingFinished = true;
MintFinished();
goalReached = (this.balance > mintingGoal);
return true;
}
}
revert();
}
/**
* @dev Function refunds contributors if ICO was unsuccesful
* @return bool True if conditions for refund are met false otherwise.
*/
function refund() returns(bool) {
if (mintingFinished == true && goalReached == false && alreadyMintedOnce == true) {
uint256 valueOfInvestment = this.balance.mul(balances[msg.sender]).div(totalSupply);
totalSupply.sub(balances[msg.sender]);
RefundRequest(valueOfInvestment,msg.sender,balances[msg.sender]);
balances[msg.sender] = 0;
msg.sender.transfer(valueOfInvestment);
return true;
}
revert();
}
}
contract TitsToken is MintableToken {
string public name = "Truth In The Sourcecode";
string public symbol = "TITS";
uint public decimals = 18;
uint public voitingStartTime;
address public votedAddress;
uint public votedYes = 1;
uint public votedNo = 0;
event VoteOnTransferStarted(address indexed beneficiaryContract);
event RegisterTransferBeneficiaryContract(address indexed beneficiaryContract);
event VotingEnded(address indexed beneficiaryContract, bool result);
event ShareHolderVoted(address adr,uint256 votes,bool isYesVote);
uint public constant VOTING_PREPARE_TIMESPAN = 7 days;
uint public constant VOTING_TIMESPAN = 7 days;
uint public failedVotingCount = 0;
bool public isVoting = false;
bool public isVotingPrepare = false;
address public beneficiaryContract = address(0);
mapping(address => uint256) public votesAvailable;
address[] public voters;
/**
* @dev voting long enought to go to next phase
*/
modifier votingLong() {
if (getNow() - voitingStartTime < VOTING_TIMESPAN) revert();
_;
}
/**
* @dev preparation for voting (application for voting) long enought to go to next phase
*/
modifier votingPrepareLong() {
if (getNow() - voitingStartTime < VOTING_PREPARE_TIMESPAN) revert();
_;
}
/**
* @dev Voting started and in progress
*/
modifier votingInProgress() {
if (isVoting == false) revert();
_;
}
modifier votingNotInProgress() {
if (isVoting == true) revert();
_;
}
/**
* @dev Voting preparation started and in progress
*/
modifier votingPrepareInProgress() {
if (isVotingPrepare == false) revert();
_;
}
/**
* @dev Voters agreed on proposed contract and Ethereum is being send to that contract
*/
function sendToBeneficiaryContract() {
if (beneficiaryContract != address(0)) {
beneficiaryContract.transfer(this.balance);
} else {
revert();
}
}
/**
* @dev can be called by anyone, if timespan withou accepted proposal long enought
* enables refund
*/
function registerVotingPrepareFailure() mintingClosed{
if(getNow()-mintingStartTime>(2+failedVotingCount)*maxMintingTime ){
failedVotingCount=failedVotingCount+1;
if (failedVotingCount == 10) {
goalReached = false;
}
}
}
/**
* @dev opens preparation for new voting on proposed Lottery Contract address
*/
function startVotingPrepare(address votedAddressArg) mintingClosed votingNotInProgress IsMintingGoal onlyOwner{
isVoting = false;
isVotingPrepare = true;
RegisterTransferBeneficiaryContract(votedAddressArg);
votedAddress = votedAddressArg;
voitingStartTime = getNow();
for (uint i = 0; i < voters.length; i++) {
delete voters[i];
}
delete voters;
}
/**
* @dev payable so attendance only of people who really care
* registers You as a voter;
*/
function registerForVoting() payable votingPrepareInProgress {
if (msg.value >= 10 finney) {
voters.push(msg.sender);
}
else{
revert();
}
}
/**
* @dev opens voting on proposed Lottery Contract address
*/
function startVoting() votingPrepareInProgress votingPrepareLong {
VoteOnTransferStarted(votedAddress);
for (uint256 i = 0; i < voters.length; i++) {
address voter = voters[i];
uint256 votes = balanceOf(voter);
votesAvailable[voter]=votes;
}
isVoting = true;
voitingStartTime = getNow();
isVotingPrepare = false;
}
/**
* @dev closes voting on proposed Lottery Contract address
* checks if failed - if No votes is more common than yes increase failed voting count and if it reaches 10
* reach of goal is failing and investors can withdraw their money
*/
function closeVoring() votingInProgress votingLong {
VotingEnded(votedAddress, votedYes > votedNo);
isVoting = false;
isVotingPrepare = false;
if (votedYes > votedNo) {
beneficiaryContract = votedAddress;
} else {
failedVotingCount = failedVotingCount + 1;
if (failedVotingCount == 10) {
goalReached = false;
}
}
}
/**
* @dev votes on contract proposal
*/
function vote(bool isVoteYes) votingInProgress{
uint256 votes = votesAvailable[msg.sender];
ShareHolderVoted(msg.sender,votes,isVoteYes);
if (isVoteYes) {
votesAvailable[msg.sender] = 0;
votedYes = votedYes.add(votes);
}
else
if (isVoteYes==false) {
votesAvailable[msg.sender] = 0;
votedNo = votedNo.add(votes);
}
else{
revert();
}
}
}
|
closes voting on proposed Lottery Contract address checks if failed - if No votes is more common than yes increase failed voting count and if it reaches 10 reach of goal is failing and investors can withdraw their money/
|
function closeVoring() votingInProgress votingLong {
VotingEnded(votedAddress, votedYes > votedNo);
isVoting = false;
isVotingPrepare = false;
if (votedYes > votedNo) {
beneficiaryContract = votedAddress;
failedVotingCount = failedVotingCount + 1;
if (failedVotingCount == 10) {
goalReached = false;
}
}
}
| 12,878,118
|
// SPDX-License-Identifier: MIT-open-group
pragma solidity ^0.8.11;
import "contracts/libraries/StakingNFT/StakingNFT.sol";
/// @custom:salt ValidatorStaking
/// @custom:deploy-type deployUpgradeable
contract ValidatorStaking is StakingNFT {
constructor() StakingNFT() {}
function initialize() public initializer onlyFactory {
__stakingNFTInit("AVSNFT", "AVS");
}
/// mint allows a staking position to be opened. This function
/// requires the caller to have performed an approve invocation against
/// AToken into this contract. This function will fail if the circuit
/// breaker is tripped.
function mint(uint256 amount_)
public
override
withCircuitBreaker
onlyValidatorPool
returns (uint256 tokenID)
{
return _mintNFT(msg.sender, amount_);
}
/// mintTo allows a staking position to be opened in the name of an
/// account other than the caller. This method also allows a lock to be
/// placed on the position up to _MAX_MINT_LOCK . This function requires the
/// caller to have performed an approve invocation against AToken into
/// this contract. This function will fail if the circuit breaker is
/// tripped.
function mintTo(
address to_,
uint256 amount_,
uint256 lockDuration_
) public override withCircuitBreaker onlyValidatorPool returns (uint256 tokenID) {
require(
lockDuration_ <= _MAX_MINT_LOCK,
string(
abi.encodePacked(StakingNFTErrorCodes.STAKENFT_LOCK_DURATION_GREATER_THAN_MINT_LOCK)
)
);
tokenID = _mintNFT(to_, amount_);
if (lockDuration_ > 0) {
_lockPosition(tokenID, lockDuration_);
}
return tokenID;
}
/// burn exits a staking position such that all accumulated value is
/// transferred to the owner on burn.
function burn(uint256 tokenID_)
public
override
onlyValidatorPool
returns (uint256 payoutEth, uint256 payoutAToken)
{
return _burn(msg.sender, msg.sender, tokenID_);
}
/// burnTo exits a staking position such that all accumulated value
/// is transferred to a specified account on burn
function burnTo(address to_, uint256 tokenID_)
public
override
onlyValidatorPool
returns (uint256 payoutEth, uint256 payoutAToken)
{
return _burn(msg.sender, to_, tokenID_);
}
}
|
burn exits a staking position such that all accumulated value is transferred to the owner on burn.
|
function burn(uint256 tokenID_)
public
override
onlyValidatorPool
returns (uint256 payoutEth, uint256 payoutAToken)
{
return _burn(msg.sender, msg.sender, tokenID_);
}
| 6,410,299
|
./partial_match/4/0x27C70Cd1946795B66be9d954418546998b546634/sources/DigitalaxPodeNFT.sol
|
Allows a whitelisted admin to update the end date of the pode/ If already passed, dont allow opening again Only allow setting this once Lock future end time modifications
|
function updatePodeEnd(uint256 _end) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxPodeNFT.updatePodeEnd: Sender must be admin"
);
require(podeEndTimestamp > _getNow(), "DigitalaxPodeNFT.updatePodeEnd: End time already passed");
require(!podeEndTimestampLocked, "DigitalaxPodeNFT.updatePodeEnd: End time locked");
podeEndTimestamp = _end;
podeEndTimestampLocked = true;
emit PodeEndUpdated(podeEndTimestamp, _msgSender());
}
| 8,764,330
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.7.0 <0.9.0;
import "./test.sol";
import "../contracts/Dao.sol";
import "../contracts/DaoContract.sol";
interface CheatCodes {
function prank(address) external;
function expectRevert(bytes calldata) external;
}
string constant NullString = "";
bytes constant NullBytes = "";
address constant NullAddress = address(0);
contract DaoTest is DSTest {
CheatCodes cheats = CheatCodes(HEVM_ADDRESS);
Dao dao;
string public gDaoName = "MyDao";
address public gTopicAddress = 0x0000000000000000000000000000000000012345;
uint32 public gMaxUsers = 100000;
uint256 gBatchSize = 1000;
uint32 gAccessUpdateAuthIdentifier = 0x853d9ed4;
uint32 gRemovalAuthIdentifier = 0x04939f12;
uint32 gNotUserIdentifier = 0x51ef2234;
address[] public gUsers = [
address(0x1),
address(0x2),
address(0x3),
address(0x4),
address(0x5),
address(0x6),
address(0x7),
address(0x8),
address(0x9)];
receive() external payable { }
function setUp() public {
dao = new Dao(gDaoName, gTopicAddress, address(this));
}
// =================
// Utility Functions
// =================
function CreateErorrCallData(uint32 _identifier, uint256 _arg1) internal pure returns(bytes memory){
return abi.encodePacked(_identifier, _arg1);
}
function CreateErorrCallData(uint32 _identifier, uint256 _arg1, uint256 _arg2) internal pure returns(bytes memory){
return abi.encodePacked(_identifier, _arg1, _arg2);
}
function bytesCmp(bytes memory a, bytes memory b) public pure returns(bool){
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
function addAUserNoImpersonateNoRevert(address user, AccessType userLevel) public {
addAUserNoImpersonate(user, userLevel, NullBytes);
}
function addAUserNoImpersonateWithRevert(address user, AccessType userLevel, bytes memory revertMessage) public {
addAUserNoImpersonate(user, userLevel, revertMessage);
}
function addAUserNoImpersonate(address user, AccessType userLevel, bytes memory revertMessage) public {
addAUser(user, userLevel, NullAddress, revertMessage);
}
function addAUserWithImpersonateNoRevert(address user, AccessType userLevel, address impersonateAs) public {
addAUserWithImpersonate(user, userLevel, impersonateAs, NullBytes);
}
function addAUserWithImpersonateWithRevert(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
addAUserWithImpersonate(user, userLevel, impersonateAs, revertMessage);
}
function addAUserWithImpersonate(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
addAUser(user, userLevel, impersonateAs, revertMessage);
}
function addAUser(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
address[] memory param = new address[](1);
param[0] = user;
AccessType origUserLevel = dao.getUser(user);
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.addUser(param, userLevel);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(userLevel));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function removeAUserNoImpersonateNoRevert(address user) public {
removeAUserNoImpersonate(user, NullBytes);
}
function removeAUserNoImpersonateWithRevert(address user, bytes memory revertMessage) public {
removeAUserNoImpersonate(user, revertMessage);
}
function removeAUserNoImpersonate(address user, bytes memory revertMessage) public {
removeAUser(user, NullAddress, revertMessage);
}
function removeAUserWithImpersonateNoRevert(address user, address impersonateAs) public {
removeAUserWithImpersonate(user, impersonateAs, NullBytes);
}
function removeAUserWithImpersonateWithRevert(address user, address impersonateAs, bytes memory revertMessage) public {
removeAUserWithImpersonate(user, impersonateAs, revertMessage);
}
function removeAUserWithImpersonate(address user, address impersonateAs, bytes memory revertMessage) public {
removeAUser(user, impersonateAs, revertMessage);
}
function removeAUser(address user, address impersonateAs, bytes memory revertMessage) public {
address[] memory param = new address[](1);
param[0] = user;
AccessType origUserLevel = dao.getUser(user);
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeUser(param);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(0));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function removeUsersNoImpersonateNoRevert(address[] memory users) public {
removeUsersNoImpersonate(users, NullBytes);
}
function removeUsersNoImpersonateWithRevert(address[] memory users, bytes memory revertMessage) public {
removeUsersNoImpersonate(users, revertMessage);
}
function removeUsersNoImpersonate(address[] memory users, bytes memory revertMessage) public {
removeUsers(users, NullAddress, revertMessage);
}
function removeUsersWithImpersonateNoRevert(address[] memory users, address impersonateAs) public {
removeUsersWithImpersonate(users, impersonateAs, NullBytes);
}
function removeUsersWithImpersonateWithRevert(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
removeUsersWithImpersonate(users, impersonateAs, revertMessage);
}
function removeUsersWithImpersonate(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
removeUsers(users, impersonateAs, revertMessage);
}
function removeUsers(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
AccessType[] memory originalUserLevels = new AccessType[](users.length);
for (uint i = 0; i < users.length; i++){
originalUserLevels[i] = dao.getUser(users[i]);
}
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeUser(users);
if(expectSuccess){
for(uint i = 0; i < users.length; i++){
assertEq(uint(dao.getUser(users[i])), uint(0));
}
} else {
for (uint i = 0; i < users.length; i++){
assertEq(uint(dao.getUser(users[i])), uint(originalUserLevels[i]));
}
}
}
function removeAnOfficerNoImpersonateNoRevert(address user) public {
removeAnOfficerNoImpersonate(user, NullBytes);
}
function removeAnOfficerNoImpersonateWithRevert(address user, bytes memory revertMessage) public {
removeAnOfficerNoImpersonate(user, revertMessage);
}
function removeAnOfficerNoImpersonate(address user, bytes memory revertMessage) public {
removeAnOfficer(user, NullAddress, revertMessage);
}
function removeAnOfficerWithImpersonateNoRevert(address user, address impersonateAs) public {
removeAnOfficerWithImpersonate(user, impersonateAs, NullBytes);
}
function removeAnOfficerWithImpersonateWithRevert(address user, address impersonateAs, bytes memory revertMessage) public {
removeAnOfficerWithImpersonate(user, impersonateAs, revertMessage);
}
function removeAnOfficerWithImpersonate(address user, address impersonateAs, bytes memory revertMessage) public {
removeAnOfficer(user, impersonateAs, revertMessage);
}
function removeAnOfficer(address user, address impersonateAs, bytes memory revertMessage) public {
bool expectSuccess = true;
AccessType origUserLevel = dao.getUser(user);
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeOfficer(user);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(0));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function addMaxUsers(bool batched, AccessType level, uint256 batchSize) public {
uint160 i;
uint32 batches;
uint256 numUsersToAdd = gMaxUsers - dao.getUserCount();
// Force non batched if maxUsers is less than batchSize
if (gMaxUsers < batchSize){
batched = false;
}
if(batched){
address[] memory batch = new address[](batchSize);
// Add users in batches minus the last batch witch may be
// not a whole batch of batchSize.
for ( ;i < (numUsersToAdd - numUsersToAdd % batchSize); i++){
// Add user to batch
batch[i%batch.length] = address(i);
// Only send the batch to the contract when its full
if((i%batch.length) == (batch.length-1)){
emit log_named_uint("Batch", batches++);
dao.addUser(batch, level);
}
}
}
// If batched, now send final batch (not full batch)
// If non batched, send all users now in a single batch
if((numUsersToAdd - i) > 0) {
address[] memory finalBatch = new address[](numUsersToAdd - i);
for (uint160 j = 0; i < numUsersToAdd; i++)
{
finalBatch[j++] = address(i);
}
emit log_named_uint("- Batch", batches++);
dao.addUser(finalBatch, level);
}
assertEq(dao.getUserCount(), gMaxUsers);
}
// ===================================================
// ============
// Test getters
// ============
function testGetDaoNameBase() public {
assertEq(dao.getDaoName(), gDaoName);
}
function testGetMaxUsersBase() public {
assertEq(dao.getMaxUsers(), gMaxUsers);
}
function testGetTopicAddressBase() public {
assertEq(dao.getTopicAddress(), gTopicAddress);
}
function testGetUserCountBase() public {
assertEq(dao.getUserCount(), 1);
}
function testGetUserBase() public {
assertEq(uint(dao.getUser(address(this))), uint(AccessType.Officer));
}
function testGetBalance() public {
assertEq(dao.getBalance(), 0);
}
// ============
// Test setters
// ============
function testSetMaxUsers() public {
uint32 newMaxUsers = 500000;
dao.setMaxUsers(newMaxUsers);
assertEq(dao.getMaxUsers(), newMaxUsers);
dao.setMaxUsers(gMaxUsers);
assertEq(dao.getMaxUsers(), gMaxUsers);
}
function testSetMaxUsersAsNonOwner() public {
cheats.prank(gUsers[1]);
cheats.expectRevert('Only owner is allowed');
dao.setMaxUsers(1234);
}
// ==================================
// Test adding Member user via addUser
// ==================================
function testAddUserMemberAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
}
function testAddUserMemberAsMember() public {
// Add gUsers[1] as a member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test adding Admin user via addUser
// ==================================
function testAddUserAdminAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
}
function testAddUserAdminAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ====================================
// Test adding Officer user via addUser
// ====================================
function testAddUserOfficerAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
cheats.prank(gUsers[1]);
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =========================================
// Test removing Member user via removeUser
// =========================================
function testRemoveUserMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserMemberAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserMemberAsOfficer() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
// =========================================
// Test removing Admin user via removeUser
// =========================================
function testRemoveUserAdminAsOwner() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserAdminAsAdmin() public {
// Add gUsers[1] and gUsers[2] as Admins
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
// =========================================
// Test removing Officer user via removeUser
// =========================================
function testRemoveUserOfficerAsOwner() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Admin), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserOfficerAsAdmin() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Admin
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserOfficerAsOfficer() public {
// Add gUsers[1] and gUsers[2] as Officers
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Officer
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ============================================
// Test removing Officer user via removeOfficer
// ============================================
function testRemoveOfficerAsOwner() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as the owner
removeAnOfficerNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveOfficerAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
function testRemoveOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
function testRemoveOfficerAsOfficer() public {
// Add gUsers[1] and gUsers[2] as Officers
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
// ==========================
// Test Adding MaxUsers Users
// ==========================
function testAddMaxUsersAsMemberBatched() public {
addMaxUsers(true, AccessType.Member, gBatchSize);
}
function testAddMaxUsersAsMemberNonBatched() public {
addMaxUsers(false, AccessType.Member, gBatchSize);
}
function testAddMaxUsersAsAdminBatched() public {
addMaxUsers(true, AccessType.Admin, gBatchSize);
}
function testAddMaxUsersAsAdminNonBatched() public {
addMaxUsers(false, AccessType.Admin, gBatchSize);
}
function testAddMaxUsersAsOfficerBatched() public {
addMaxUsers(true, AccessType.Officer, gBatchSize);
}
function testAddMaxUsersAsOfficerNonBatched() public {
addMaxUsers(false, AccessType.Officer, gBatchSize);
}
// ============================
// Test Adding MaxUsers+1 Users
// ============================
function testAddMaxUsersPlusAddMemberBatched() public {
addMaxUsers(true, AccessType.Member, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Member, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddMemberNonBatched() public {
addMaxUsers(false, AccessType.Member, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Member, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddAdminBatched() public {
addMaxUsers(true, AccessType.Admin, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Admin, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddAdminNonBatched() public {
addMaxUsers(false, AccessType.Admin, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Admin, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddOfficerBatched() public {
addMaxUsers(true, AccessType.Officer, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Officer, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddOfficerNonBatched() public {
addMaxUsers(false, AccessType.Officer, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Officer, "Max Users Exceeded");
}
// ===============================
// Test Adding a Member user twice
// ===============================
function testAddUserTwiceMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as a member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceMemberAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ===============================
// Test Adding an Admin user twice
// ===============================
function testAddUserTwiceAdminAsOwner() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceAdminAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test Adding an Officer user twice
// =================================
function testAddUserTwiceOfficerAsOwner() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as an Officer
addAUserNoImpersonateWithRevert(gUsers[1], AccessType.Officer, CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Admin), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test Removing a Member user twice
// =================================
function testRemoveUserTwiceMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Admin)));
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserTwiceMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserTwiceMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
// =================================
// Test Removing an Admin user twice
// =================================
function testRemoveUserTwiceAdminAsOwner() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Admin)));
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserTwiceAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
// ===================================
// Test Removing an Officer user twice
// ===================================
function testRemoveOfficerTwiceAsOwner() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAnOfficerNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAnOfficerNoImpersonateWithRevert(gUsers[1], "Not an officer");
assertEq(dao.getUserCount(), 1);
}
// ==============================
// Test Removing users in batches
// ==============================
function testRemoveUsersBatched() public {
for(uint i = 0; i < gUsers.length; i++){
addAUserNoImpersonateNoRevert(gUsers[i], AccessType.Member);
}
assertEq(dao.getUserCount(), 10);
removeUsersNoImpersonateNoRevert(gUsers);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUsersBatchedNonExistingUser() public {
address[] memory copy = new address[](gUsers.length);
for(uint i = 0; i < gUsers.length; i++){
addAUserNoImpersonateNoRevert(gUsers[i], AccessType.Member);
copy[i] = gUsers[i];
}
assertEq(dao.getUserCount(), 10);
copy[4] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[4]))));
assertEq(dao.getUserCount(), 10);
copy[4] = gUsers[4];
copy[0] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[0]))));
assertEq(dao.getUserCount(), 10);
copy[0] = gUsers[0];
copy[gUsers.length-1] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[gUsers.length-1]))));
assertEq(dao.getUserCount(), 10);
}
// =================================================
// Test sending/receiving funds to/from the contract
// =================================================
function testDeposit() public {
assertEq(dao.getBalance(), 0);
payable(address(dao)).transfer(1);
assertEq(dao.getBalance(), 1);
payable(address(dao)).transfer(10);
assertEq(dao.getBalance(), 11);
}
function testWithdrawl() public {
assertEq(dao.getBalance(), 0);
payable(address(dao)).transfer(10);
uint256 bal_before = address(this).balance;
dao.transferHbar(payable(address(this)), 1);
assertEq(bal_before, address(this).balance - 1);
}
function testWithdrawlRevert() public {
assertEq(dao.getBalance(), 0);
cheats.expectRevert("");
dao.transferHbar(payable(address(this)), 1);
}
// ================================
// Test promoting a Member to Admin
// ================================
function testPromoteMemberToAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test promoting a Member to Officer
// ==================================
function testPromoteMemberToOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test promoting an Admin to Officer
// ==================================
function testPromoteAdminToOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteAdminToOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteAdminToOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test demoting an Officer to Amdin
// =================================
function testDemoteOfficerToAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test demoting an Officer to Member
// ==================================
function testDemoteOfficerToMemberAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ================================
// Test demoting an Admin to Member
// ================================
function testDemoteAdminToMemberAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteAdminToMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testDemoteAdminToMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
}
|
Add gUsers[1] as an Admin Have gUsers[1] try to add gUsers[2] as an Admin
|
function testAddUserAdminAsAdmin() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
| 14,053,765
|
./full_match/4/0x7b6ecD8b59C76F83E04D43a4B5bF0Fb178787cf1/sources/DAODinos_-_Working_Safe_Math.sol
|
GET ALL BANANAS OF A WALLET AS AN ARRAY OF STRINGS. WOULD BE BETTER MAYBE IF IT RETURNED A STRUCT WITH ID-NAME MATCH Return an empty array
|
function daoDinoNamesOfOwner(address _owner) external view returns(string[] memory ) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new string[](0);
string[] memory result = new string[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = daoDinosNames[ tokenOfOwnerByIndex(_owner, index) ] ;
}
return result;
}
}
| 13,315,005
|
pragma solidity >=0.4.21 <0.7.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721Metadata.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/lifecycle/Pausable.sol";
/**
* @title A digital relationship between two entities
* @author Michael McLaughlin
* @notice You can use this contract for basic warranties
*/
contract Warranty is ERC721Metadata, ReentrancyGuard, Pausable {
using SafeMath for uint256;
using Math for uint256;
using Address for address payable;
mapping(uint256 => address) public _pendingTransfer;
mapping(address => uint256) public _balances;
Claim[] public _claims;
struct Claim {
address warrantor;
uint256 value;
uint256 valuation;
uint256 expiresAfter;
uint256 activatedAt;
uint256 delayTime;
bool redeemed;
bool fulfilled;
bool terminated;
}
event BalanceUpdated(address indexed account, uint256 amount, uint256 balance, bool negative);
event Withdrawn(address indexed account, address indexed target, uint256 amount, uint256 balance);
event Redeemed(uint256 indexed tokenId, address indexed warrantor, address indexed warrantee, bool redeemed);
event Fulfilled(uint256 indexed tokenId, address indexed warrantor, address indexed warrantee, bool redeemed);
event Terminated(uint256 indexed tokenId, address indexed account);
event WarrantorshipChanged(uint256 indexed tokenId, address indexed warrantor);
event ClaimBalanceUpdated(uint256 indexed tokenId, uint256 value);
event NotesAppended(uint256 indexed tokenId, address indexed account, string notes);
constructor()
ERC721Metadata("Warrantee", "WRNT")
ReentrancyGuard()
Pausable()
public
{}
function () external payable {
require(false, "fallback function use not allowed");
}
/**
* @notice Allows only the two entities to run operation
* @param tokenId uint256 ID is the token in question
*/
modifier warranteeOrWarrantorOnly(uint256 tokenId) {
require((
isWarrantee(msg.sender, tokenId) ||
isWarrantor(msg.sender, tokenId)
), "sender must either be the token owner (warrantee) or the warrantor");
_;
}
/**
* @notice Allows only the warrantee of a claim to operate
* @param tokenId uint256 ID is the token in question
*/
modifier warranteeOnly(uint256 tokenId) {
require(isWarrantee(msg.sender, tokenId), "sender must be the owner of the token");
_;
}
/**
* @notice Allows only the warrantor of a claim to operate
* @param tokenId uint256 ID is the token in question
*/
modifier warrantorOnly(uint256 tokenId) {
require(isWarrantor(msg.sender, tokenId), "sender must be the warrantor of the token");
_;
}
/**
* @notice Allows only non redeemed tokens to be operated upon
* @param tokenId uint256 ID is the token in question
*/
modifier notRedeemedOnly(uint256 tokenId) {
require(!_claims[tokenId].redeemed, "only non redeemed claims can use this method");
_;
}
/**
* @notice Allows only non terminated tokens to be operated upon
* @param tokenId uint256 ID is the token in question
*/
modifier notTerminatedOnly(uint256 tokenId) {
require(!_claims[tokenId].terminated, "only non terminated claims can use this method");
_;
}
/**
* @notice Allows only non expired tokens to be operated upon
* @param tokenId uint256 ID is the token in question
*/
modifier notExpiredOnly(uint256 tokenId) {
require(
_claims[tokenId].activatedAt == 0 ||
_claims[tokenId].activatedAt.add(_claims[tokenId].delayTime).add(_claims[tokenId].expiresAfter) > timestamp(),
"only non expired claims can use this method"
);
_;
}
/**
* @notice Requires two values to be greater than or equal
* when compared to one another
* @param a uint256 is the first value, which must be greater than or equal to the second parameter
* @param b uint256 is the second value, which must be less than or equal to the first parameter
*/
modifier greaterThanOrEqual(uint256 a, uint256 b) {
require(a >= b, "a must be greater than or equal to b");
_;
}
/**
* @notice Checks whether a given token is owned by a particular address
* @param warrantee address is the owner in question
* @param tokenId uint256 is the token in question
*/
modifier checkWarranteeOf(address warrantee, uint256 tokenId) {
if (warrantee != address(0)) { // any owner is honored
require(isWarrantee(warrantee, tokenId), "must be working with the correct warrantee");
}
_;
}
/**
* @notice Makes sure that the account passed is the owner of the token
* @param account address is the address being checked against
* @param tokenId uint256 ID is the token in question
* @return matches as bool whether the account is indeed the owner of the token
*/
function isWarrantee(address account, uint256 tokenId) public view returns(bool matches) {
return account == this.ownerOf(tokenId);
}
/**
* @notice Makes sure that the account passed is set as the token's warrantor
* @param account address is the address being checked against
* @param tokenId uint256 ID is the token in question
* @return matches as bool whether the account is indeed the warrantor of the token
*/
function isWarrantor(address account, uint256 tokenId) public view returns(bool matches) {
return account == _claims[tokenId].warrantor;
}
function timestamp() internal view returns(uint256) {
return block.timestamp;
}
/**
* @notice Checks the balance of a given account
* @param account address to check the balance credited by the contract
* @return amount as uint256 as the balance credited to the account and available for withdrawal
*/
function balance(address account) public view returns(uint256 amount) {
return _balances[account];
}
/**
* @notice Extend the timeline until the claim expires
* @param tokenId uint256 as the targeted token
* @param expiryTime uint256 as the amount of time to be added to the expiry time first set when the claim was created
* @param delayTime uint256 as the amount of time to be added to the delay time first set to zero
*/
function extendClaimExpiration(uint256 tokenId, uint256 expiryTime, uint256 delayTime)
public
whenNotPaused
warrantorOnly(tokenId)
notTerminatedOnly(tokenId)
notRedeemedOnly(tokenId)
// ensure no overflow occurs
greaterThanOrEqual(_claims[tokenId].activatedAt.add(delayTime).add(expiryTime), _claims[tokenId].activatedAt)
{
_claims[tokenId].delayTime = _claims[tokenId].delayTime.add(delayTime);
_claims[tokenId].expiresAfter = _claims[tokenId].expiresAfter.add(expiryTime);
}
/**
* @notice Updates a given account's credited balance.
* @param account address to be credited or debited
* @param amount uint256 is the amount to add or subtract
* @param negative bool defines whether or not the value should be added or subtracted
*/
function updateBalance(address account, uint256 amount, bool negative) internal {
if (amount == 0) return;
if (negative) {
_balances[account] = _balances[account].sub(amount);
} else {
_balances[account] = _balances[account].add(amount);
}
emit BalanceUpdated(account, amount, _balances[account], negative);
}
function creditAccount(address payee, uint256 amount) internal {
updateBalance(payee, amount, false);
}
function debitAccount(address payer, uint256 amount) internal {
updateBalance(payer, amount, true);
}
/**
* @notice Deposits eth and directly credits an account
* @param account address to send the eth to
*/
function depositToAccount(address account) public payable whenNotPaused {
creditAccount(account, msg.value);
}
/**
* @notice Warrantor can fulfill the claim for the amount agreed upon when the claim was first created.
* @param warrantee address to check ownership of the token (optional)
* @param tokenId uint256 the id of the token in question
*/
function fulfillClaim(address warrantee, uint256 tokenId)
public
payable
whenNotPaused
warrantorOnly(tokenId)
checkWarranteeOf(warrantee, tokenId)
{
Claim storage claim = _claims[tokenId];
// if the warrantor sends more than enough or has enough in their balance
uint256 bal = balance(msg.sender);
debitAccount(msg.sender, bal); // guarantor temporarily has zero balance
uint256 value = claim.value.add(msg.value).add(bal);
require(value >= claim.valuation, "claim can only be fullfilled for the original agreed upon valuation");
creditAccount(msg.sender, value.sub(claim.valuation));
creditAccount(this.ownerOf(tokenId), claim.valuation);
updateClaimValue(tokenId, 0); // remove funds locked in claim
claim.fulfilled = true;
emit Fulfilled(tokenId, msg.sender, warrantee, claim.redeemed);
_terminateClaim(tokenId);
}
function _terminateClaim(uint256 tokenId)
internal
notTerminatedOnly(tokenId)
{
Claim storage claim = _claims[tokenId];
if (!claim.fulfilled && claim.value != 0) {
// should only have value assigned, to be divii'd up if claim has not been fulfilled
uint256 elapsed = claim.expiresAfter.sub(timeToClaimExpire(tokenId));
uint256 leftover = claim.value.mul(claim.expiresAfter).sub(claim.value.mul(elapsed)).div(claim.expiresAfter);
creditAccount(this.ownerOf(tokenId), leftover);
creditAccount(claim.warrantor, claim.value.sub(leftover));
}
claim.terminated = true;
updateClaimValue(tokenId, 0); // remove funds locked in claim
emit Terminated(tokenId, msg.sender);
}
/**
* @notice Terminates the claim in question. Ends the claim completely and hands all funds over to the warrantor.
* disallow redeemed tokens from being terminated
* @param tokenId uint256 is the targeted token
*/
function terminateClaim(uint256 tokenId)
public
whenNotPaused
warranteeOnly(tokenId)
notRedeemedOnly(tokenId)
{
_terminateClaim(tokenId);
}
/**
* @notice Releases funds credited to the sender to a given account
* @dev account param will, in most cases, be the sender's address
* @dev nonReentrant modifier used to prevent double spends
* @param account address the account to send the eth to
* @param amount uint256 the amount of eth to send to the account
*/
function releaseTo(address payable account, uint256 amount)
public
nonReentrant
whenNotPaused
greaterThanOrEqual(_balances[msg.sender], amount)
{
address payable sender = msg.sender;
address payable target = account;
if (address(0) == target) {
target = sender;
}
debitAccount(sender, amount);
target.sendValue(amount);
emit Withdrawn(sender, target, amount, _balances[sender]);
}
/**
* @notice Creates and guarantees a claim
* @param warrantee address is the new owner of the token
* @param warrantor address is the new recipient of the funds of the contract
* @param valuation uint256 is the value agreed that is required to fulfill the claim at the end of its life
* @param expiresAfter uint256 creates a window in seconds within which a claim can be redeemed to be subesequently fulfilled.
* @param tokenURI optional string provides the token uri in json format: https://eips.ethereum.org/EIPS/eip-721
* @return tokenId uint256 sends back the tokenId created
*/
function createAndFundClaim(
address payable warrantee,
address payable warrantor,
uint256 valuation,
uint256 expiresAfter,
string memory tokenURI
)
public
payable
returns(uint256)
{
uint256 tokenId = createClaim(warrantee, valuation, expiresAfter, tokenURI);
transferWarrantorship(tokenId, warrantor);
fundClaim(tokenId, msg.value);
return tokenId;
}
/**
* @notice transfers the warrantor of the erc721 to another owner
* @param tokenId uint256 the token to transfer
* @param account address the account to transfer to
*/
function transferWarrantorship(uint256 tokenId, address account)
public
whenNotPaused
notExpiredOnly(tokenId)
warranteeOnly(tokenId)
{
_activateClaim(tokenId);
_claims[tokenId].warrantor = account;
emit WarrantorshipChanged(tokenId, account);
}
/**
* @notice provides the full timeline for a given claim's expiration
* @param tokenId uint256 defines the token in question
* @return expireTime uint256 defines when the claim will no longer be redeemable by the warrantee
*/
function claimExpireTime(uint256 tokenId)
public
view
whenNotPaused
returns(uint256 expireTime)
{
return _claims[tokenId].activatedAt.add(_claims[tokenId].delayTime).add(_claims[tokenId].expiresAfter);
}
/**
* @notice provides the number of seconds until the expireTime will be reached
* @param tokenId uint256 the token in question
* @return timeUntil uint256 defines the number of seconds until the expireTime is met
*/
function timeToClaimExpire(uint256 tokenId)
public
view
whenNotPaused
returns(uint256 timeUntil)
{
uint256 expireTime = claimExpireTime(tokenId);
uint256 tsmp = timestamp();
if (expireTime <= tsmp) {
return 0;
}
return expireTime.sub(tsmp);
}
/**
* @notice Guarantees a claim by claiming responsibility for the other side of the transaction, the warrantor
* also useful when being sold a warranty by another warrantor or by the warrantee
* @param tokenId uint256 targets a specific token
*/
function guaranteeClaim(uint256 tokenId, uint256 value)
public
payable
whenNotPaused
notRedeemedOnly(tokenId)
notTerminatedOnly(tokenId)
{
Claim storage claim = _claims[tokenId];
require((
_pendingTransfer[tokenId] == msg.sender
), "unable to hand off claim unless it is first posted for transfer");
// activatedAt will not yet be set if first time
uint256 availableCredit = balance(msg.sender).add(msg.value);
require(availableCredit >= claim.value, "available credit must meet or exceed claim value");
require(value >= claim.value, "claim must preserve currently backed value");
address previousOwner = this.ownerOf(tokenId);
creditAccount(previousOwner, claim.value); // give back the value provided by previous warrantor
claim.value = 0; // reset value
fundClaim(tokenId, value); // back claim with new and old value
transferFrom(previousOwner, msg.sender, tokenId); // transfer token
setApprovalForAll(previousOwner, false); // disallow previous owner to move token
_pendingTransferClaim(tokenId, address(0));
}
function _activateClaim(uint256 tokenId) internal {
if (_claims[tokenId].activatedAt == 0) {
_claims[tokenId].activatedAt = timestamp();
}
}
/**
* @notice Posts a claim to be picked up "guaranteed" by another entity
* @dev can only sell if the token is not already being sold
* @param tokenId uint256 the targeted token
* @param account address the buyer to pick up the claim
*/
function postClaim(uint256 tokenId, address account)
public
whenNotPaused
warranteeOnly(tokenId)
{
require(_pendingTransfer[tokenId] == address(0), "only claims that are not being sold can be put up for sale");
_pendingTransfer[tokenId] = account;
approve(account, tokenId);
}
/**
* @notice Un-posts a claim that was previously posted.
* If there is a disagreement, the warrantee can refuse the transfer
* @param tokenId uint256 the targeted token
*/
function depostClaim(uint256 tokenId)
public
whenNotPaused
warranteeOnly(tokenId)
{
require(_pendingTransfer[tokenId] != address(0), "only claims that are being sold can be deposted");
_pendingTransferClaim(tokenId, address(0));
}
function _pendingTransferClaim(uint256 tokenId, address account) internal {
_pendingTransfer[tokenId] = account;
}
/**
* @notice Fund a claim
* @notice anybody can add to a claim's value. value will only be accessable to the owner
* @dev only funds if the claim has not already been terminated.
* Otherwise it would go directly to the warrantor or the warrantee if it was redeemed.
* That's just confusing.
* @param tokenId uint256 the token to be targeted
*/
function fundClaim(uint256 tokenId, uint256 amount)
public
payable
notTerminatedOnly(tokenId)
{
depositToAccount(msg.sender);
creditClaim(tokenId, amount);
debitAccount(msg.sender, amount);
}
function creditClaim(uint256 tokenId, uint256 value) internal {
if (value != 0) {
updateClaimValue(tokenId, _claims[tokenId].value.add(value));
}
}
function updateClaimValue(uint256 tokenId, uint256 value) internal {
if (_claims[tokenId].value != value) {
_claims[tokenId].value = value;
emit ClaimBalanceUpdated(tokenId, value);
}
}
/**
* @notice De-Redeems a claim. Allows for warrantee or warrantor to reset time if guarantee's submission did not meet agreement, or for any other reason
* @dev Can only be completed by the warrantee or warrantor.
* only warrantor adds extra time. transactions would be no-ops if they came from user, or at worst would waste the tx fees from the business
* @param tokenId uint256 targets a token
* @param expiryTime uint256 adds more time (in seconds) to the expiration decay
* @param delayTime uint256 adds more time to the delay offset (in seconds)
*/
function deredeemClaim(uint256 tokenId, uint256 expiryTime, uint256 delayTime)
public
whenNotPaused
warranteeOrWarrantorOnly(tokenId)
{
require(_claims[tokenId].redeemed, "only a redeemed claim can be reset");
_claims[tokenId].redeemed = false;
emit Redeemed(tokenId, _claims[tokenId].warrantor, this.ownerOf(tokenId), _claims[tokenId].redeemed);
if (msg.sender == _claims[tokenId].warrantor) {
extendClaimExpiration(tokenId, expiryTime, delayTime);
}
}
function refundClaim(uint256 tokenId)
public
whenNotPaused
warrantorOnly(tokenId)
// can be expired, just not terminated
notTerminatedOnly(tokenId)
{
creditAccount(this.ownerOf(tokenId), _claims[tokenId].value);
_claims[tokenId].value = 0;
_terminateClaim(tokenId);
}
/**
* @notice Redeems a claim such that an account is notified that it needs to be fulfilled
* if claim is accepted guarantee will get the funds defined in valuation back
* @param tokenId targets a given token
*/
function redeemClaim(uint256 tokenId)
public
whenNotPaused
warranteeOnly(tokenId)
notRedeemedOnly(tokenId)
notTerminatedOnly(tokenId)
{
require(!_claims[tokenId].redeemed, "claim cannot be redeemed");
_claims[tokenId].redeemed = true;
emit Redeemed(tokenId, _claims[tokenId].warrantor, this.ownerOf(tokenId), _claims[tokenId].redeemed);
}
/**
* @notice overwrites an internal safeMint to allow anyone to mint their own
* could probably be gotten rid of if a factory was used instead
* @param to address the address to assign ownership of the newly minted token to
* @param tokenId uint256 the id of the token to be minted
* @param _data bytes a set of bytes to hold with the tokenId
*/
function safeMint(address to, uint256 tokenId, bytes memory _data) public returns (bool) {
_safeMint(to, tokenId, _data);
return true;
}
/**
* @notice Create a claim by minting it yourself or any given contract
* @notice A distinct Uniform Resource Identifier (URI) for a given asset.
* @dev safeMint is used so integrating with a contract should be possible
* @param warrantee address is the address that should own the token to start
* @param valuation holds the agreed upon valuation of the claim
* @param expiresAfter holds the number of seconds after the claim is guaranteed by a warrantor that the warranty should expire
* @param tokenURI optional string provides the token uri in json format: https://eips.ethereum.org/EIPS/eip-721
* @return tokenId uint256 sends back the tokenId created
*/
function createClaim(
address warrantee,
uint256 valuation,
uint256 expiresAfter,
string memory tokenURI
)
public
whenNotPaused
returns(uint256)
{
uint256 tokenId = _claims.length;
require(expiresAfter < 100000000000, "expires after value cannot be too large");
_safeMint(warrantee, tokenId);
if (bytes(tokenURI).length > 0) {
_setTokenURI(tokenId, tokenURI);
}
// metadata to associate with the id
_claims.push(Claim({
valuation: valuation,
// set when the claim is guaranteed
value: 0,
warrantor: warrantee,
activatedAt: 0,
delayTime: 0,
// only need approximations
expiresAfter: expiresAfter,
redeemed: false,
fulfilled: false,
terminated: false
}));
return tokenId;
}
/**
* @notice adds notes to a particular claim
* @param tokenId uint256 the token to target
* @param notes optional string the notes to append
*/
function addNotes(
uint256 tokenId,
string memory notes
)
public
warranteeOrWarrantorOnly(tokenId)
{
if (bytes(notes).length > 0) {
emit NotesAppended(tokenId, msg.sender, notes);
}
}
}
|
Updates a given account's credited balance. account address to be credited or debited amount uint256 is the amount to add or subtract negative bool defines whether or not the value should be added or subtracted/
|
function updateBalance(address account, uint256 amount, bool negative) internal {
if (amount == 0) return;
function extendClaimExpiration(uint256 tokenId, uint256 expiryTime, uint256 delayTime)
public
whenNotPaused
warrantorOnly(tokenId)
notTerminatedOnly(tokenId)
notRedeemedOnly(tokenId)
greaterThanOrEqual(_claims[tokenId].activatedAt.add(delayTime).add(expiryTime), _claims[tokenId].activatedAt)
}
if (negative) {
_balances[account] = _balances[account].sub(amount);
_balances[account] = _balances[account].add(amount);
}
emit BalanceUpdated(account, amount, _balances[account], negative);
} else {
}
| 7,242,685
|
./partial_match/1/0x8183703E9DF90ed76bec0b0b8fAD33f2c024Be59/sources/KingOfEthResourcesInterface.sol
|
Determine the resource type of a tile _x The x coordinate of the top left corner of the tile _y The y coordinate of the top left corner of the tile
|
function resourceType(uint _x, uint _y)
public
pure
returns(ResourceType resource)
{
uint _seed = (_x + 7777777) ^ _y;
if(0 == _seed % 97)
{
return ResourceType.URANIUM;
}
else if(0 == _seed % 29)
{
return ResourceType.OIL;
}
else if(0 == _seed % 23)
{
return ResourceType.STEEL;
}
else if(0 == _seed % 17)
{
return ResourceType.GOLD;
}
else if(0 == _seed % 11)
{
return ResourceType.BRONZE;
}
else if(0 == _seed % 5)
{
return ResourceType.WOOD;
}
else if(0 == _seed % 2)
{
return ResourceType.CORN;
}
else
{
return ResourceType.ORE;
}
}
| 4,454,661
|
./full_match/1/0x9DaeFAaD9a31ae7Cab8916cdBcBD9f109c688260/sources/contracts/Pricer.sol
|
Gets the latest price of the asset return uint256 The latest price of the asset/
|
function getLatestPrice() external view override returns (uint256) {
return prices[latestPriceId].price;
}
| 4,947,606
|
./full_match/137/0x63464916388dAB4f2e80551250335490C4518D37/sources/contracts/WhiteBlackList/WhiteBlackListBase/WhiteBlackListBase.sol
|
solhint-disable-next-line func-name-mixedcase
|
function __WhiteBlackListBase_init(address _registry) internal onlyInitializing {
_require(
IERC165Upgradeable(_registry).supportsInterface(type(IAccessControlUpgradeable).interfaceId),
Errors.ADDRESS_NOT_SUPPORTED.selector
);
registry = _registry;
__ERC165_init();
}
| 4,758,383
|
./partial_match/56/0xe357fEd031FdDabc6348ef264997C5E2845e4d7d/sources/TomToken.sol
|
Deposit LP tokens to MasterChef for TOM allocation.
|
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accTomPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeTomTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accTomPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 11,240,610
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.0;
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { _transfer, ETH } from "./FGelato.sol";
// solhint-disable max-states-count
// solhint-disable max-line-length
contract TaskTreasuryMatic is Ownable, ReentrancyGuard {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
uint256 public maxFee;
mapping(address => mapping(address => uint256)) public userTokenBalance;
mapping(address => EnumerableSet.AddressSet) internal _tokenCredits;
EnumerableSet.AddressSet internal _whitelistedServices;
address payable public immutable gelato;
event FundsDeposited(address indexed sender, address indexed token, uint256 indexed amount);
event FundsWithdrawn(address indexed receiver, address indexed initiator, address indexed token, uint256 amount);
constructor(address payable _gelato) {
gelato = _gelato;
maxFee = 1 ether;
}
modifier onlyWhitelistedServices() {
require(_whitelistedServices.contains(msg.sender), "TaskTreasury: onlyWhitelistedServices");
_;
}
/// @notice Function to deposit Funds which will be used to execute transactions on various services
/// @param _receiver Address receiving the credits
/// @param _token Token to be credited, use "0xeeee...." for ETH
/// @param _amount Amount to be credited
function depositFunds(
address _receiver,
address _token,
uint256 _amount
) external payable {
uint256 depositAmount;
if (_token == ETH) {
depositAmount = msg.value;
} else {
IERC20 token = IERC20(_token);
uint256 preBalance = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 postBalance = token.balanceOf(address(this));
depositAmount = postBalance - preBalance;
}
userTokenBalance[_receiver][_token] = userTokenBalance[_receiver][_token] + depositAmount;
if (!_tokenCredits[_receiver].contains(_token)) _tokenCredits[_receiver].add(_token);
emit FundsDeposited(_receiver, _token, depositAmount);
}
/// @notice Function to withdraw Funds back to the _receiver
/// @param _receiver Address receiving the credits
/// @param _token Token to be credited, use "0xeeee...." for ETH
/// @param _amount Amount to be credited
function withdrawFunds(
address payable _receiver,
address _token,
uint256 _amount
) external nonReentrant {
uint256 balance = userTokenBalance[msg.sender][_token];
uint256 withdrawAmount = Math.min(balance, _amount);
userTokenBalance[msg.sender][_token] = balance - withdrawAmount;
_transfer(_receiver, _token, withdrawAmount);
if (withdrawAmount == balance) _tokenCredits[msg.sender].remove(_token);
emit FundsWithdrawn(_receiver, msg.sender, _token, withdrawAmount);
}
/// @notice Function called by whitelisted services to handle payments, e.g. PokeMe"
/// @param _token Token to be used for payment by users
/// @param _amount Amount to be deducted
/// @param _user Address of user whose balance will be deducted
function useFunds(
address _token,
uint256 _amount,
address _user
) external onlyWhitelistedServices {
if (maxFee != 0) require(maxFee >= _amount, "TaskTreasury: useFunds: Overchared");
userTokenBalance[_user][_token] = userTokenBalance[_user][_token] - _amount;
if (userTokenBalance[_user][_token] == 0) _tokenCredits[_user].remove(_token);
_transfer(gelato, _token, _amount);
}
// Governance functions
/// @notice Add new service that can call useFunds. Gelato Governance
/// @param _service New service to add
function addWhitelistedService(address _service) external onlyOwner {
require(!_whitelistedServices.contains(_service), "TaskTreasury: addWhitelistedService: whitelisted");
_whitelistedServices.add(_service);
}
/// @notice Remove old service that can call useFunds. Gelato Governance
/// @param _service Old service to remove
function removeWhitelistedService(address _service) external onlyOwner {
require(_whitelistedServices.contains(_service), "TaskTreasury: addWhitelistedService: !whitelisted");
_whitelistedServices.remove(_service);
}
/// @notice Change maxFee charged by Gelato (only relevant on Layer2s)
/// @param _newMaxFee New Max Fee to charge
function setMaxFee(uint256 _newMaxFee) external onlyOwner {
maxFee = _newMaxFee;
}
// View Funcs
/// @notice Helper func to get all deposited tokens by a user
/// @param _user User to get the balances from
function getCreditTokensByUser(address _user) external view returns (address[] memory) {
uint256 length = _tokenCredits[_user].length();
address[] memory creditTokens = new address[](length);
for (uint256 i; i < length; i++) {
creditTokens[i] = _tokenCredits[_user].at(i);
}
return creditTokens;
}
function getWhitelistedServices() external view returns (address[] memory) {
uint256 length = _whitelistedServices.length();
address[] memory whitelistedServices = new address[](length);
for (uint256 i; i < length; i++) {
whitelistedServices[i] = _whitelistedServices.at(i);
}
return whitelistedServices;
}
}
|
Function to deposit Funds which will be used to execute transactions on various services _receiver Address receiving the credits _token Token to be credited, use "0xeeee...." for ETH _amount Amount to be credited
|
function depositFunds(
address _receiver,
address _token,
uint256 _amount
) external payable {
uint256 depositAmount;
if (_token == ETH) {
depositAmount = msg.value;
IERC20 token = IERC20(_token);
uint256 preBalance = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), _amount);
uint256 postBalance = token.balanceOf(address(this));
depositAmount = postBalance - preBalance;
}
userTokenBalance[_receiver][_token] = userTokenBalance[_receiver][_token] + depositAmount;
if (!_tokenCredits[_receiver].contains(_token)) _tokenCredits[_receiver].add(_token);
emit FundsDeposited(_receiver, _token, depositAmount);
}
| 2,486,609
|
./full_match/4/0x4f97a6D1fcf56bE844D6b7510A21F407e9101d1e/sources/Users/toni/gits/erc721OZ/contracts/Freeverse.sol
|
Set a distinct base URI for a given universe. _universeId Idx for which we want URI. _URI String representing base URI./
|
function setBaseURI(
uint256 _universeId,
string memory _URI
)
external
onlyOwner
{
universeIdToBaseURI[_universeId] = _URI;
}
| 13,318,182
|
./partial_match/1/0x99577D3DD4DE7B31DFd034D465cF725FdCC5271B/sources/AMERICANPEPE.sol
|
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 {IERC20Base-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,
"ERC20Base: decreased allowance below zero"
)
);
return true;
}
| 3,714,187
|
./full_match/1/0x35f470aEF8CE51dE53B4a835168726c4179b1132/sources/contracts/staking/LockedStaking/LockedStaking.sol
|
Returns factory address/
|
function factory() external view returns (address) {
return address(_factory);
}
| 4,931,367
|
./full_match/80001/0x982AC3596520B9Fc8bae24d6AB65c5dFE3d7Cc10/sources/publish/GoldenBullFactory.sol
|
this low-level function should be called from a contract which performs important safety checks
|
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'GoldenBull: INSUFFICIENT_OUTPUT_AMOUNT');
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'GoldenBull: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'GoldenBull: INVALID_TO');
if (data.length > 0) IGoldenBullCallee(to).goldenBullCall(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'GoldenBull: INSUFFICIENT_INPUT_AMOUNT');
uint balance0Adjusted = (balance0.mul(10000).sub(amount0In.mul(25)));
uint balance1Adjusted = (balance1.mul(10000).sub(amount1In.mul(25)));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(10000**2), 'GoldenBull: K');
| 9,515,195
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./YoloInterfaces.sol";
/**
Manages the state of the PLayers in the Yolo Games Universe.
*/
contract YoloRegistry is Ownable, Pausable {
event YoloGamertagUpdate(address indexed account, string gamertag);
event YoloClantagUpdate(address indexed account, string clantag);
event YoloProfilePicUpdate(address indexed account, string pfp);
struct Player {
string gamertag;
string clantag;
string pfp;
}
mapping (address => string) public gamertags;
mapping (address => string) public clantags;
mapping (address => string) public pfps;
mapping (string => address) public gamertagToPlayer;
uint public gamertagFee = 50 ether;
uint public clantagFee = 50 ether;
uint public pfpFee = 100 ether;
uint16 public gamertagMaxLength = 80;
uint16 public clantagMaxLength = 8;
IYoloDice public diceV1;
IYoloChips public chips;
constructor(address _diceV1, address _chips) {
diceV1 = IYoloDice(_diceV1);
chips = IYoloChips(_chips);
}
// Pausable.
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
// Setters.
function setDiceV1(address _diceV1) external onlyOwner {
diceV1 = IYoloDice(_diceV1);
}
function setChips(address _chips) external onlyOwner {
chips = IYoloChips(_chips);
}
function setGamertagFee(uint256 _fee) external onlyOwner {
gamertagFee = _fee;
}
function setClantagFee(uint256 _fee) external onlyOwner {
clantagFee = _fee;
}
function setPfpFee(uint256 _fee) external onlyOwner {
pfpFee = _fee;
}
function setGamertagMaxLength(uint16 _length) external onlyOwner {
gamertagMaxLength = _length;
}
function setClantagMaxLength(uint16 _length) external onlyOwner {
clantagMaxLength = _length;
}
function setMultiGamertags(string[] memory _gamertags, address[] memory _addresses) external onlyOwner {
for (uint256 idx = 0; idx < _gamertags.length; idx++) {
// Max length.
require(bytes(_gamertags[idx]).length <= gamertagMaxLength, "Yolo Registry: Gamertag too long");
// Ensure unique.
require(!_isGamertagTaken(_gamertags[idx]), "Yolo Registry: Gamertag is taken");
_setGamertagFor(_gamertags[idx], _addresses[idx]);
}
}
// Dashboard functionality.
/// @notice Returns token IDs of V1 Dice owned by the address.
function getV1Dice(address _address) public view returns (uint256[] memory) {
uint balance = diceV1.balanceOf(_address);
uint256[] memory diceIds = new uint256[](balance);
for (uint256 idx = 0; idx < balance; idx++) {
diceIds[idx] = diceV1.tokenOfOwnerByIndex(_address, idx);
}
return diceIds;
}
/// @notice Returns the profile of the given address.
function getProfile(address _address) public view returns (Player memory) {
return Player(getGamertag(_address), getClantag(_address), getPfp(_address));
}
/// @notice Returns the full profile for the player with the given gamertag.
function getProfileForTag(string memory _gamertag) public view returns (Player memory) {
address playerAddress = gamertagToPlayer[_gamertag];
if (playerAddress == address(0x0)) {
return Player("", "", "");
}
return Player(
getGamertag(playerAddress),
getClantag(playerAddress),
getPfp(playerAddress)
);
}
function getGamertag(address _address) public view returns (string memory) {
return gamertags[_address];
}
function setGamertag(string memory _gamertag) public whenNotPaused {
// Max length.
require(bytes(_gamertag).length <= gamertagMaxLength, "Yolo Registry: Gamertag too long");
// Ensure unique.
require(!_isGamertagTaken(_gamertag), "Yolo Registry: Gamertag is taken");
chips.spend(msg.sender, gamertagFee);
_setGamertagFor(_gamertag, msg.sender);
}
function getClantag(address _address) public view returns (string memory) {
return clantags[_address];
}
function setClantag(string memory _clantag) public whenNotPaused {
// Max length.
require(bytes(_clantag).length <= clantagMaxLength, "Yolo Registry: Clantag too long");
chips.spend(msg.sender, clantagFee);
clantags[msg.sender] = _clantag;
emit YoloClantagUpdate(msg.sender, _clantag);
}
function getPfp(address _address) public view returns (string memory) {
return pfps[_address];
}
function setPfp(string memory _pfp) public whenNotPaused {
chips.spend(msg.sender, pfpFee);
pfps[msg.sender] = _pfp;
emit YoloProfilePicUpdate(msg.sender, _pfp);
}
// Helpers.
function _setGamertagFor(string memory _gamertag, address _address) internal {
// Free up old gamertag.
string memory previous = gamertags[_address];
if (bytes(previous).length > 0) {
gamertagToPlayer[previous] = address(0x0);
}
// Set new gamertag.
gamertags[_address] = _gamertag;
gamertagToPlayer[_gamertag] = _address;
emit YoloGamertagUpdate(_address, _gamertag);
}
function _isGamertagTaken(string memory _gamertag) internal view returns (bool) {
return gamertagToPlayer[_gamertag] != address(0x0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
interface IYoloDice {
/// @notice IERC721, returns owner of token.
function ownerOf(uint256 tokenId) external view returns (address);
/// @notice IERC721, returns number of tokens owned.
function balanceOf(address owner) external view returns (uint256);
/// @notice IERC721, returns total number of tokens created.
function totalSupply() external view returns (uint256);
/// @notice IERC721Enumerable, returns token ID.
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
}
interface IYoloChips {
/// @notice IERC20, returns number of tokens owned.
function balanceOf(address account) external view returns (uint256);
/// @notice Burns chips from whitelisted contracts.
function spend(address account, uint256 amount) external;
/// @notice Performs accounting before properties are transferred.
function updateOwnership(address _from, address _to) external;
}
interface IYoloBoardDeed {
/// @notice IERC721, returns number of tokens owned.
function balanceOf(address owner) external view returns (uint256);
/// @notice IERC721Enumerable, returns token ID.
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/// @notice Returns yield of the given token.
function yieldRate(uint256 tokenId) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
|
Returns the profile of the given address.
|
function getProfile(address _address) public view returns (Player memory) {
return Player(getGamertag(_address), getClantag(_address), getPfp(_address));
}
| 12,040,051
|
pragma solidity ^0.5.2 <0.6.0;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library RLP {
uint constant DATA_SHORT_START = 0x80;
uint constant DATA_LONG_START = 0xB8;
uint constant LIST_SHORT_START = 0xC0;
uint constant LIST_LONG_START = 0xF8;
uint constant DATA_LONG_OFFSET = 0xB7;
uint constant LIST_LONG_OFFSET = 0xF7;
struct RLPItem {
uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes.
uint _unsafe_length; // Number of bytes. This is the full length of the string.
}
struct Iterator {
RLPItem _unsafe_item; // Item that's being iterated over.
uint _unsafe_nextPtr; // Position of the next item in the list.
}
/* Iterator */
function next(Iterator memory self) internal pure returns (RLPItem memory subItem) {
if(hasNext(self)) {
uint256 ptr = self._unsafe_nextPtr;
uint256 itemLength = _itemLength(ptr);
subItem._unsafe_memPtr = ptr;
subItem._unsafe_length = itemLength;
self._unsafe_nextPtr = ptr + itemLength;
}
else
revert();
}
function next(Iterator memory self, bool strict) internal pure returns (RLPItem memory subItem) {
subItem = next(self);
if(strict && !_validate(subItem))
revert();
return subItem;
}
function hasNext(
Iterator memory self
) internal pure returns (bool) {
RLP.RLPItem memory item = self._unsafe_item;
return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length;
}
/* RLPItem */
/// @dev Creates an RLPItem from an array of RLP encoded bytes.
/// @param self The RLP encoded bytes.
/// @return An RLPItem
function toRLPItem(bytes memory self) internal pure returns (RLPItem memory) {
uint len = self.length;
if (len == 0) {
return RLPItem(0, 0);
}
uint memPtr;
assembly {
memPtr := add(self, 0x20)
}
return RLPItem(memPtr, len);
}
/// @dev Creates an RLPItem from an array of RLP encoded bytes.
/// @param self The RLP encoded bytes.
/// @param strict Will throw if the data is not RLP encoded.
/// @return An RLPItem
function toRLPItem(bytes memory self, bool strict) internal pure returns (RLPItem memory) {
RLP.RLPItem memory item = toRLPItem(self);
if(strict) {
uint len = self.length;
if(_payloadOffset(item) > len)
revert();
if(_itemLength(item._unsafe_memPtr) != len)
revert();
if(!_validate(item))
revert();
}
return item;
}
/// @dev Check if the RLP item is null.
/// @param self The RLP item.
/// @return 'true' if the item is null.
function isNull(RLPItem memory self) internal pure returns (bool ret) {
return self._unsafe_length == 0;
}
/// @dev Check if the RLP item is a list.
/// @param self The RLP item.
/// @return 'true' if the item is a list.
function isList(RLPItem memory self) internal pure returns (bool ret) {
if (self._unsafe_length == 0)
return false;
uint memPtr = self._unsafe_memPtr;
assembly {
ret := iszero(lt(byte(0, mload(memPtr)), 0xC0))
}
}
/// @dev Check if the RLP item is data.
/// @param self The RLP item.
/// @return 'true' if the item is data.
function isData(RLPItem memory self) internal pure returns (bool ret) {
if (self._unsafe_length == 0)
return false;
uint memPtr = self._unsafe_memPtr;
assembly {
ret := lt(byte(0, mload(memPtr)), 0xC0)
}
}
/// @dev Check if the RLP item is empty (string or list).
/// @param self The RLP item.
/// @return 'true' if the item is null.
function isEmpty(RLPItem memory self) internal pure returns (bool ret) {
if(isNull(self))
return false;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
return (b0 == DATA_SHORT_START || b0 == LIST_SHORT_START);
}
/// @dev Get the number of items in an RLP encoded list.
/// @param self The RLP item.
/// @return The number of items.
function items(RLPItem memory self) internal pure returns (uint) {
if (!isList(self))
return 0;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
uint pos = memPtr + _payloadOffset(self);
uint last = memPtr + self._unsafe_length - 1;
uint itms;
while(pos <= last) {
pos += _itemLength(pos);
itms++;
}
return itms;
}
/// @dev Create an iterator.
/// @param self The RLP item.
/// @return An 'Iterator' over the item.
function iterator(RLPItem memory self) internal pure returns (Iterator memory it) {
require(isList(self));
uint ptr = self._unsafe_memPtr + _payloadOffset(self);
it._unsafe_item = self;
it._unsafe_nextPtr = ptr;
}
/// @dev Return the RLP encoded bytes.
/// @param self The RLPItem.
/// @return The bytes.
function toBytes(RLPItem memory self) internal pure returns (bytes memory bts) {
uint256 len = self._unsafe_length;
if (len == 0)
return bts;
bts = new bytes(len);
_copyToBytes(self._unsafe_memPtr, bts, len);
//
// uint256 len = self._unsafe_length;
//
// if (len == 0) {
// return bts;
// } else if (len == 1) {
// bts = new bytes(len);
// _copyToBytes(self._unsafe_memPtr, bts, len);
// return bts;
// }
//
// bts = new bytes(len-_payloadOffset(self));
// uint start = self._unsafe_memPtr + _payloadOffset(self);
// _copyToBytes(start, bts, len-_payloadOffset(self));
}
/// @dev Decode an RLPItem into bytes. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toData(RLPItem memory self) internal pure returns (bytes memory bts) {
require(isData(self));
(uint256 rStartPos, uint256 len) = _decode(self);
bts = new bytes(len);
_copyToBytes(rStartPos, bts, len);
}
/// @dev Get the list of sub-items from an RLP encoded list.
/// Warning: This is inefficient, as it requires that the list is read twice.
/// @param self The RLP item.
/// @return Array of RLPItems.
function toList(RLPItem memory self) internal pure returns (RLPItem[] memory list) {
require(isList(self));
uint256 numItems = items(self);
list = new RLPItem[](numItems);
RLP.Iterator memory it = iterator(self);
uint idx;
while(hasNext(it)) {
list[idx] = next(it);
idx++;
}
}
/// @dev Decode an RLPItem into an ascii string. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toAscii(RLPItem memory self) internal pure returns (string memory str) {
require(isData(self));
(uint256 rStartPos, uint256 len) = _decode(self);
bytes memory bts = new bytes(len);
_copyToBytes(rStartPos, bts, len);
str = string(bts);
}
/// @dev Decode an RLPItem into a uint. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toUint(RLPItem memory self) internal pure returns (uint data) {
require(isData(self));
(uint256 rStartPos, uint256 len) = _decode(self);
require(len <= 32);
assembly {
data := div(mload(rStartPos), exp(256, sub(32, len)))
}
}
/// @dev Decode an RLPItem into a boolean. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toBool(RLPItem memory self) internal pure returns (bool data) {
require(isData(self));
(uint256 rStartPos, uint256 len) = _decode(self);
require(len == 1);
uint temp;
assembly {
temp := byte(0, mload(rStartPos))
}
require(temp == 1 || temp == 0);
return temp == 1 ? true : false;
}
/// @dev Decode an RLPItem into a byte. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toByte(RLPItem memory self)
internal
pure
returns (byte data)
{
require(isData(self));
(uint256 rStartPos, uint256 len) = _decode(self);
require(len == 1);
byte temp;
assembly {
temp := byte(0, mload(rStartPos))
}
return temp;
}
/// @dev Decode an RLPItem into an int. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toInt(RLPItem memory self)
internal
pure
returns (int data)
{
return int(toUint(self));
}
/// @dev Decode an RLPItem into a bytes32. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toBytes32(RLPItem memory self)
internal
pure
returns (bytes32 data)
{
return bytes32(toUint(self));
}
/// @dev Decode an RLPItem into an address. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toAddress(RLPItem memory self)
internal
pure
returns (address data)
{
(, uint256 len) = _decode(self);
require(len <= 20);
return address(toUint(self));
}
// Get the payload offset.
function _payloadOffset(RLPItem memory self)
private
pure
returns (uint)
{
if(self._unsafe_length == 0)
return 0;
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
if(b0 < DATA_SHORT_START)
return 0;
if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START))
return 1;
if(b0 < LIST_SHORT_START)
return b0 - DATA_LONG_OFFSET + 1;
return b0 - LIST_LONG_OFFSET + 1;
}
// Get the full length of an RLP item.
function _itemLength(uint memPtr)
private
pure
returns (uint len)
{
uint b0;
assembly {
b0 := byte(0, mload(memPtr))
}
if (b0 < DATA_SHORT_START)
len = 1;
else if (b0 < DATA_LONG_START)
len = b0 - DATA_SHORT_START + 1;
else if (b0 < LIST_SHORT_START) {
assembly {
let bLen := sub(b0, 0xB7) // bytes length (DATA_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
} else if (b0 < LIST_LONG_START) {
len = b0 - LIST_SHORT_START + 1;
} else {
assembly {
let bLen := sub(b0, 0xF7) // bytes length (LIST_LONG_OFFSET)
let dLen := div(mload(add(memPtr, 1)), exp(256, sub(32, bLen))) // data length
len := add(1, add(bLen, dLen)) // total length
}
}
}
// Get start position and length of the data.
function _decode(RLPItem memory self)
private
pure
returns (uint memPtr, uint len)
{
require(isData(self));
uint b0;
uint start = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(start))
}
if (b0 < DATA_SHORT_START) {
memPtr = start;
len = 1;
return (memPtr, len);
}
if (b0 < DATA_LONG_START) {
len = self._unsafe_length - 1;
memPtr = start + 1;
} else {
uint bLen;
assembly {
bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET
}
len = self._unsafe_length - 1 - bLen;
memPtr = start + bLen + 1;
}
return (memPtr, len);
}
// Assumes that enough memory has been allocated to store in target.
function _copyToBytes(
uint btsPtr,
bytes memory tgt,
uint btsLen) private pure
{
// Exploiting the fact that 'tgt' was the last thing to be allocated,
// we can write entire words, and just overwrite any excess.
assembly {
{
let words := div(add(btsLen, 31), 32)
let rOffset := btsPtr
let wOffset := add(tgt, 0x20)
for { let i := 0 } lt(i, words) { i := add(i, 1) } {
let offset := mul(i, 0x20)
mstore(add(wOffset, offset), mload(add(rOffset, offset)))
}
mstore(add(tgt, add(0x20, mload(tgt))), 0)
}
}
}
// Check that an RLP item is valid.
function _validate(RLPItem memory self)
private
pure
returns (bool ret)
{
// Check that RLP is well-formed.
uint b0;
uint b1;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
b1 := byte(1, mload(memPtr))
}
if(b0 == DATA_SHORT_START + 1 && b1 < DATA_SHORT_START)
return false;
return true;
}
}
library Object {
using RLP for bytes;
using RLP for bytes[];
using RLP for RLP.RLPItem;
using RLP for RLP.Iterator;
struct Data {
uint sura;
uint ayat;
bytes text;
}
function createData(bytes memory dataBytes)
internal
pure
returns (Data memory)
{
RLP.RLPItem[] memory dataList = dataBytes.toRLPItem().toList();
return Data({
sura: dataList[0].toUint(),
ayat: dataList[1].toUint(),
text: dataList[2].toBytes()
});
}
}
contract Storage is Ownable {
using Object for bytes;
using RLP for bytes;
using RLP for bytes[];
using RLP for RLP.RLPItem;
using RLP for RLP.Iterator;
struct coord {
uint sura;
uint ayat;
}
// @dev Mapping ayat's hash with its text.
mapping(bytes32 => bytes) public content;
mapping(uint => mapping(uint => bytes32)) public coordinates;
mapping(bytes32 => coord[]) public all_coordinates;
/** @dev Adds content.
* @param text Ayat text.
* @param sura Sura number.
* @param ayat Ayat number.
*/
function add_content(
bytes memory text,
uint sura,
uint ayat
) public onlyOwner {
bytes32 hash = keccak256(text);
if (coordinates[sura][ayat] != 0x0000000000000000000000000000000000000000000000000000000000000000) {
return;
}
coordinates[sura][ayat] = hash;
all_coordinates[hash].push(coord({sura:sura, ayat: ayat}));
content[hash] = text;
}
/** @dev Adds packed data.
* @param data RLP packed objects.
*/
function add_data(bytes memory data) public onlyOwner {
RLP.RLPItem[] memory list = data.toRLPItem().toList();
for (uint index = 0; index < list.length; index++) {
RLP.RLPItem[] memory item = list[index].toList();
uint sura = item[0].toUint();
uint ayat = item[1].toUint();
bytes memory text = item[2].toData();
add_content(text, sura, ayat);
}
}
/** @dev Gets ayat text by hash.
* @param ayat_hash Ayat keccak256 hash of compressed text (gzip).
* @return Ayat compressed text.
*/
function get_ayat_text_by_hash(
bytes32 ayat_hash
) public view returns (bytes memory text) {
text = content[ayat_hash];
}
/** @dev Gets ayat text by coordinates.
* @param sura Sura number.
* @param ayat Ayat number.
* @return Ayat compressed text.
*/
function get_ayat_text_by_coordinates(
uint sura,
uint ayat
) public view returns (bytes memory text) {
bytes32 hash = coordinates[sura][ayat];
text = content[hash];
}
/** @dev Gets number of ayats by hash.
* @param hash Ayat keccak256 hash of compressed text (gzip).
* @return Ayats number.
*/
function get_ayats_length(
bytes32 hash
) public view returns (uint) {
return all_coordinates[hash].length;
}
/** @dev Gets an ayat's number and a sura number by a hash and a index in an array.
* @param hash Ayat keccak256 hash of compressed text (gzip).
* @param index Ayat index. Ayat text is not unique in the Quran, so this may be several options.
*/
function get_ayat_coordinates_by_index(
bytes32 hash,
uint index
) public view returns (uint sura, uint ayat) {
coord memory data = all_coordinates[hash][index];
sura = data.sura;
ayat = data.ayat;
}
/** @dev Verifying the text of an ayat.
* @param text Ayat compressed text (gzip).
* @return bool
*/
function check_ayat_text(
bytes memory text
) public view returns(bool) {
bytes32 hash = keccak256(text);
bytes memory ayat_data = content[hash];
return ayat_data.length != 0;
}
}
|
Creates an RLPItem from an array of RLP encoded bytes. self The RLP encoded bytes. strict Will throw if the data is not RLP encoded. return An RLPItem
|
function toRLPItem(bytes memory self, bool strict) internal pure returns (RLPItem memory) {
RLP.RLPItem memory item = toRLPItem(self);
if(strict) {
uint len = self.length;
if(_payloadOffset(item) > len)
revert();
if(_itemLength(item._unsafe_memPtr) != len)
revert();
if(!_validate(item))
revert();
}
return item;
}
| 13,008,348
|
pragma solidity ^0.4.8;
contract Token {
/// token总量,默认会为public变量生成一个getter函数接口,名称为totalSupply().
uint256 public totalSupply=52013140;
/// 获取账户_owner拥有token的数量
function balanceOf(address _owner) constant returns (uint256 balance);
//从消息发送者账户中往_to账户转数量为_value的token
function transfer(address _to, uint256 _value) returns (bool success);
//从账户_from中往账户_to转数量为_value的token,与approve方法配合使用
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
//消息发送账户设置账户_spender能从发送账户中转出数量为_value的token
function approve(address _spender, uint256 _value) returns (bool success);
//获取账户_spender可以从账户_owner中转出token的数量
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
//发生转账时必须要触发的事件
event Transfer(address indexed _from, address indexed _to, uint256 _value);
//当函数approve(address _spender, uint256 _value)成功执行时必须触发的事件
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//默认totalSupply 不会超过最大值 (2^256 - 1).
//如果随着时间的推移将会有新的token生成,则可以用下面这句避免溢出的异常
//require(balances[msg.sender] >= _value && balances[_to] + _value >balances[_to]);
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;//从消息发送者账户中减去token数量_value
balances[_to] += _value;//往接收账户增加token数量_value
Transfer(msg.sender, _to, _value);//触发转币交易事件
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
balances[_to] += _value;//接收账户增加token数量_value
balances[_from] -= _value;//支出账户_from减去token数量_value
allowed[_from][msg.sender] -= _value;//消息发送者可以从账户_from中转出的数量减少_value
Transfer(_from, _to, _value);//触发转币交易事件
return true;
}
//查询余额
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
//授权账户_spender可以从消息发送者账户转出数量为_value的token
function approve(address _spender, uint256 _value) returns (bool success)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];//允许_spender从_owner中转出的token数
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract ArtBC is StandardToken {
/* Public variables of the token */
string public name; //名称: eg Simon Bucks
uint8 public decimals ; //最多的小数位数How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //token简称: eg SBX
string public version = 'H0.1'; //版本
function ArtBC(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) {
balances[msg.sender] = _initialAmount; // 初始token数量给予消息发送者
totalSupply = _initialAmount; // 设置初始总量
name = _tokenName; // token名称
decimals = _decimalUnits; // 小数位数
symbol = _tokenSymbol; // token简称
}
/* 同意转出并调用接收合约(根据自己需求实现) */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
}
|
默认totalSupply 不会超过最大值 (2^256 - 1).如果随着时间的推移将会有新的token生成,则可以用下面这句避免溢出的异常require(balances[msg.sender] >= _value && balances[_to] + _value >balances[_to]);
|
function transfer(address _to, uint256 _value) returns (bool success) {
require(balances[msg.sender] >= _value);
return true;
}
| 1,692,903
|
./full_match/42220/0xc7B57dA5DF5424aa8b6999BEab8aFDDFdC4C8A20/sources/contracts/Router.sol
|
refund dust eth, if any
|
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = BlackfarmingLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IBlackfarmingPair(pair).mint(to);
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
| 16,330,080
|
pragma solidity ^0.4.20;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
**/
library SafeMathLib{
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @dev Abstract contract for approveAndCall.
**/
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
/**
* @title Game Tester Token
* @dev ERC20 contract utilizing ERC865-ish structure (based on the CoinvestTokenV2 contract)
* @dev to allow users to pay Ethereum fees in tokens.
**/
contract GameTesterToken is Ownable {
using SafeMathLib for uint256;
string public constant symbol = "GTCOIN";
string public constant name = "Game Tester";
uint8 public constant decimals = 18;
uint256 private _totalSupply = 100000000 * (10 ** 18);
// Function sigs to be used within contract for signature recovery.
bytes4 internal constant transferSig = 0xa9059cbb;
bytes4 internal constant approveSig = 0x095ea7b3;
bytes4 internal constant increaseApprovalSig = 0xd73dd623;
bytes4 internal constant decreaseApprovalSig = 0x66188463;
bytes4 internal constant approveAndCallSig = 0xcae9ca51;
bytes4 internal constant revokeSignatureSig = 0xe40d89e5;
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
// Keeps track of the last nonce sent from user. Used for delegated functions.
mapping (address => uint256) nonces;
// Mapping of past used hashes: true if already used.
mapping (address => mapping (bytes => bool)) invalidSignatures;
// Mapping of finalized ERC865 standard sigs => our function sigs for future-proofing
mapping (bytes4 => bytes4) public standardSigs;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed from, address indexed spender, uint tokens);
event SignatureRedeemed(bytes _sig, address indexed from);
/**
* @dev Set owner and beginning balance.
**/
constructor()
public
{
balances[msg.sender] = _totalSupply;
}
/**
* @dev This code allows us to redirect pre-signed calls with different function selectors to our own.
**/
function ()
public
{
bytes memory calldata = msg.data;
bytes4 new_selector = standardSigs[msg.sig];
require(new_selector != 0);
assembly {
mstore(add(0x20, calldata), new_selector)
}
require(address(this).delegatecall(calldata));
assembly {
if iszero(eq(returndatasize, 0x20)) { revert(0, 0) }
returndatacopy(0, 0, returndatasize)
return(0, returndatasize)
}
}
/** ******************************** ERC20 ********************************* **/
/**
* @dev Transfers coins from one address to another.
* @param _to The recipient of the transfer amount.
* @param _amount The amount of tokens to transfer.
**/
function transfer(address _to, uint256 _amount)
public
returns (bool success)
{
require(_transfer(msg.sender, _to, _amount));
return true;
}
/**
* @dev An allowed address can transfer tokens from another's address.
* @param _from The owner of the tokens to be transferred.
* @param _to The address to which the tokens will be transferred.
* @param _amount The amount of tokens to be transferred.
**/
function transferFrom(address _from, address _to, uint _amount)
public
returns (bool success)
{
require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
require(_transfer(_from, _to, _amount));
return true;
}
/**
* @dev Approves a wallet to transfer tokens on one's behalf.
* @param _spender The wallet approved to spend tokens.
* @param _amount The amount of tokens approved to spend.
**/
function approve(address _spender, uint256 _amount)
public
returns (bool success)
{
require(_approve(msg.sender, _spender, _amount));
return true;
}
/**
* @dev Increases the allowed amount for spender from msg.sender.
* @param _spender The address to increase allowed amount for.
* @param _amount The amount of tokens to increase allowed amount by.
**/
function increaseApproval(address _spender, uint256 _amount)
public
returns (bool success)
{
require(_increaseApproval(msg.sender, _spender, _amount));
return true;
}
/**
* @dev Decreases the allowed amount for spender from msg.sender.
* @param _spender The address to decrease allowed amount for.
* @param _amount The amount of tokens to decrease allowed amount by.
**/
function decreaseApproval(address _spender, uint256 _amount)
public
returns (bool success)
{
require(_decreaseApproval(msg.sender, _spender, _amount));
return true;
}
/**
* @dev Used to approve an address and call a function on it in the same transaction.
* @dev _spender The address to be approved to spend GTCOIN.
* @dev _amount The amount of GTCOIN to be approved to spend.
* @dev _data The data to send to the called contract.
**/
function approveAndCall(address _spender, uint256 _amount, bytes _data)
public
returns (bool success)
{
require(_approve(msg.sender, _spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(msg.sender, _amount, address(this), _data);
return true;
}
/** ****************************** Internal ******************************** **/
/**
* @dev Internal transfer for all functions that transfer.
* @param _from The address that is transferring coins.
* @param _to The receiving address of the coins.
* @param _amount The amount of coins being transferred.
**/
function _transfer(address _from, address _to, uint256 _amount)
internal
returns (bool success)
{
require (_to != address(0));
require(balances[_from] >= _amount);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
* @dev Internal approve for all functions that require an approve.
* @param _owner The owner who is allowing spender to use their balance.
* @param _spender The wallet approved to spend tokens.
* @param _amount The amount of tokens approved to spend.
**/
function _approve(address _owner, address _spender, uint256 _amount)
internal
returns (bool success)
{
allowed[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
return true;
}
/**
* @dev Increases the allowed by "_amount" for "_spender" from "owner"
* @param _owner The address that tokens may be transferred from.
* @param _spender The address that may transfer these tokens.
* @param _amount The amount of tokens to transfer.
**/
function _increaseApproval(address _owner, address _spender, uint256 _amount)
internal
returns (bool success)
{
allowed[_owner][_spender] = allowed[_owner][_spender].add(_amount);
emit Approval(_owner, _spender, allowed[_owner][_spender]);
return true;
}
/**
* @dev Decreases the allowed by "_amount" for "_spender" from "_owner"
* @param _owner The owner of the tokens to decrease allowed for.
* @param _spender The spender whose allowed will decrease.
* @param _amount The amount of tokens to decrease allowed by.
**/
function _decreaseApproval(address _owner, address _spender, uint256 _amount)
internal
returns (bool success)
{
if (allowed[_owner][_spender] <= _amount) allowed[_owner][_spender] = 0;
else allowed[_owner][_spender] = allowed[_owner][_spender].sub(_amount);
emit Approval(_owner, _spender, allowed[_owner][_spender]);
return true;
}
/** ************************ Delegated Functions *************************** **/
/**
* @dev Called by delegate with a signed hash of the transaction data to allow a user
* @dev to transfer tokens without paying gas in Ether (they pay in GTCOIN instead).
* @param _signature Signed hash of data for this transfer.
* @param _to The address to transfer GTCOIN to.
* @param _value The amount of GTCOIN to transfer.
* @param _gasPrice Price (IN GTCOIN) that will be paid per unit of gas by user to "delegate".
* @param _nonce Nonce of the user's new transaction (to make signatures unique, not to be confused with address transaction nonce).
**/
function transferPreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
// Log starting gas left of transaction for later gas price calculations.
uint256 gas = gasleft();
// Recover signer address from signature; ensure address is valid.
address from = recoverPreSigned(_signature, transferSig, _to, _value, "", _gasPrice, _nonce);
require(from != address(0));
// Require the hash has not been used, declare it used, increment nonce.
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
// Internal transfer.
require(_transfer(from, _to, _value));
// If the delegate is charging, pay them for gas in GTCOIN.
if (_gasPrice > 0) {
// 35000 because of base fee of 21000 and ~14000 for the fee transfer.
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev Called by a delegate with signed hash to approve a transaction for user.
* @dev All variables equivalent to transfer except _to:
* @param _to The address that will be approved to transfer GTCOIN from user's wallet.
**/
function approvePreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverPreSigned(_signature, approveSig, _to, _value, "", _gasPrice, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_approve(from, _to, _value));
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev Used to increase the amount allowed for "_to" to spend from "from"
* @dev A bare approve allows potentially nasty race conditions when using a delegate.
**/
function increaseApprovalPreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverPreSigned(_signature, increaseApprovalSig, _to, _value, "", _gasPrice, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_increaseApproval(from, _to, _value));
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev Added for the same reason as increaseApproval. Decreases to 0 if "_value" is greater than allowed.
**/
function decreaseApprovalPreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverPreSigned(_signature, decreaseApprovalSig, _to, _value, "", _gasPrice, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_decreaseApproval(from, _to, _value));
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev approveAndCallPreSigned allows a user to approve a contract and call a function on it
* @dev in the same transaction. As with the other presigneds, a delegate calls this with signed data from user.
* @dev This function is the big reason we're using gas price and calculating gas use.
* @dev Using this with the contract can result in varying gas costs.
* @param _extraData The data to send to the contract.
**/
function approveAndCallPreSigned(
bytes _signature,
address _to,
uint256 _value,
bytes _extraData,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(356)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverPreSigned(_signature, approveAndCallSig, _to, _value, _extraData, _gasPrice, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_approve(from, _to, _value));
ApproveAndCallFallBack(_to).receiveApproval(from, _value, address(this), _extraData);
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/** *************************** Revoke PreSigned ************************** **/
/**
* @dev Revoke signature without going through a delegate.
* @param _sigToRevoke The signature that you no longer want to be used.
**/
function revokeSignature(bytes _sigToRevoke)
public
returns (bool)
{
invalidSignatures[msg.sender][_sigToRevoke] = true;
emit SignatureRedeemed(_sigToRevoke, msg.sender);
return true;
}
/**
* @dev Revoke signature through a delegate.
* @param _signature The signature allowing this revocation.
* @param _sigToRevoke The signature that you would like revoked.
* @param _gasPrice The amount of token wei to be paid for each uint of gas.
**/
function revokeSignaturePreSigned(
bytes _signature,
bytes _sigToRevoke,
uint256 _gasPrice)
public
validPayload(356)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverRevokeHash(_signature, _sigToRevoke, _gasPrice);
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
invalidSignatures[from][_sigToRevoke] = true;
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
/**
* @dev Get hash for a revocation.
* @param _sigToRevoke The signature to be revoked.
* @param _gasPrice The amount to be paid to delegate for sending this tx.
**/
function getRevokeHash(bytes _sigToRevoke, uint256 _gasPrice)
public
pure
returns (bytes32 txHash)
{
return keccak256(revokeSignatureSig, _sigToRevoke, _gasPrice);
}
/**
* @dev Recover the address from a revocation signature.
* @param _sigToRevoke The signature to be revoked.
* @param _signature The signature allowing this revocation.
* @param _gasPrice The amount of token wei to be paid for each unit of gas.
**/
function recoverRevokeHash(bytes _signature, bytes _sigToRevoke, uint256 _gasPrice)
public
pure
returns (address from)
{
return ecrecoverFromSig(getSignHash(getRevokeHash(_sigToRevoke, _gasPrice)), _signature);
}
/** ************************** PreSigned Constants ************************ **/
/**
* @dev Used in frontend and contract to get hashed data of any given pre-signed transaction.
* @param _to The address to transfer GTCOIN to.
* @param _value The amount of GTCOIN to be transferred.
* @param _extraData Extra data of tx if needed. Transfers and approves will leave this null.
* @param _function Function signature of the pre-signed function being used.
* @param _gasPrice The agreed-upon amount of GTCOIN to be paid per unit of gas.
* @param _nonce The user's nonce of the new transaction.
**/
function getPreSignedHash(
bytes4 _function,
address _to,
uint256 _value,
bytes _extraData,
uint256 _gasPrice,
uint256 _nonce)
public
view
returns (bytes32 txHash)
{
return keccak256(address(this), _function, _to, _value, _extraData, _gasPrice, _nonce);
}
/**
* @dev Recover an address from a signed pre-signed hash.
* @param _sig The signed hash.
* @param _function The function signature for function being called.
* @param _to The address to transfer/approve/transferFrom/etc. tokens to.
* @param _value The amont of tokens to transfer/approve/etc.
* @param _extraData The extra data included in the transaction, if any.
* @param _gasPrice The amount of token wei to be paid to the delegate for each unit of gas.
* @param _nonce The user's nonce for this transaction.
**/
function recoverPreSigned(
bytes _sig,
bytes4 _function,
address _to,
uint256 _value,
bytes _extraData,
uint256 _gasPrice,
uint256 _nonce)
public
view
returns (address recovered)
{
return ecrecoverFromSig(getSignHash(getPreSignedHash(_function, _to, _value, _extraData, _gasPrice, _nonce)), _sig);
}
/**
* @dev Add signature prefix to hash for recovery à la ERC191.
* @param _hash The hashed transaction to add signature prefix to.
**/
function getSignHash(bytes32 _hash)
public
pure
returns (bytes32 signHash)
{
return keccak256("\x19Ethereum Signed Message:\n32", _hash);
}
/**
* @param hash The hash of signed data for the transaction.
* @param sig Contains r, s, and v for recovery of address from the hash.
**/
function ecrecoverFromSig(bytes32 hash, bytes sig)
public
pure
returns (address recoveredAddress)
{
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) return address(0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
}
// Albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28]
// geth uses [0, 1] and some clients have followed. This might change, see https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) return address(0);
return ecrecover(hash, v, r, s);
}
/**
* @dev Frontend queries to find the next nonce of the user so they can find the new nonce to send.
* @param _owner Address that will be sending the GTCOIN.
**/
function getNonce(address _owner)
external
view
returns (uint256 nonce)
{
return nonces[_owner];
}
/** ****************************** Constants ******************************* **/
/**
* @dev Return total supply of token.
**/
function totalSupply()
external
view
returns (uint256)
{
return _totalSupply;
}
/**
* @dev Return balance of a certain address.
* @param _owner The address whose balance we want to check.
**/
function balanceOf(address _owner)
external
view
returns (uint256)
{
return balances[_owner];
}
/**
* @dev Allowed amount for a user to spend of another's tokens.
* @param _owner The owner of the tokens approved to spend.
* @param _spender The address of the user allowed to spend the tokens.
**/
function allowance(address _owner, address _spender)
external
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/** ****************************** onlyOwner ******************************* **/
/**
* @dev Allow the owner to take ERC20 tokens off of this contract if they are accidentally sent.
**/
function token_escape(address _tokenContract)
external
onlyOwner
{
GameTesterToken lostToken = GameTesterToken(_tokenContract);
uint256 stuckTokens = lostToken.balanceOf(address(this));
lostToken.transfer(owner, stuckTokens);
}
/**
* @dev Owner may set the standard sig to redirect to one of our pre-signed functions.
* @dev Added in order to prepare for the ERC865 standard function names to be different from ours.
* @param _standardSig The function signature of the finalized standard function.
* @param _ourSig The function signature of our implemented function.
**/
function updateStandard(bytes4 _standardSig, bytes4 _ourSig)
external
onlyOwner
returns (bool success)
{
// These 6 are the signatures of our pre-signed functions.
require(_ourSig == 0x1296830d || _ourSig == 0x617b390b || _ourSig == 0xadb8249e ||
_ourSig == 0x8be52783 || _ourSig == 0xc8d4b389 || _ourSig == 0xe391a7c4);
standardSigs[_standardSig] = _ourSig;
return true;
}
/** ***************************** Modifiers ******************************** **/
modifier validPayload(uint _size) {
uint payload_size;
assembly {
payload_size := calldatasize
}
require(payload_size >= _size);
_;
}
}
|
Called by delegate with a signed hash of the transaction data to allow a user to transfer tokens without paying gas in Ether (they pay in GTCOIN instead). _signature Signed hash of data for this transfer. _to The address to transfer GTCOIN to. _value The amount of GTCOIN to transfer. _gasPrice Price (IN GTCOIN) that will be paid per unit of gas by user to "delegate". _nonce Nonce of the user's new transaction (to make signatures unique, not to be confused with address transaction nonce)./ Log starting gas left of transaction for later gas price calculations. Recover signer address from signature; ensure address is valid. Require the hash has not been used, declare it used, increment nonce. Internal transfer. If the delegate is charging, pay them for gas in GTCOIN. 35000 because of base fee of 21000 and ~14000 for the fee transfer.
|
function transferPreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _gasPrice,
uint256 _nonce)
public
validPayload(292)
returns (bool)
{
uint256 gas = gasleft();
address from = recoverPreSigned(_signature, transferSig, _to, _value, "", _gasPrice, _nonce);
require(from != address(0));
require(!invalidSignatures[from][_signature]);
invalidSignatures[from][_signature] = true;
nonces[from]++;
require(_transfer(from, _to, _value));
if (_gasPrice > 0) {
gas = 35000 + gas.sub(gasleft());
require(_transfer(from, msg.sender, _gasPrice.mul(gas)));
}
emit SignatureRedeemed(_signature, from);
return true;
}
| 6,343,394
|
./full_match/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/api/Orders.sol
|
Cancels order Internal function without access restriction orderId Order to cancel reason Cancellation reason
|
function _cancelOrder(uint256 orderId, string memory reason) internal {
OrderStore.Order memory order = orderStore.get(orderId);
if (order.size == 0) return;
orderStore.remove(orderId);
if (!order.isReduceOnly) {
fundStore.transferOut(order.asset, order.user, order.margin + order.fee);
}
emit OrderCancelled(orderId, order.user, reason);
}
| 11,525,685
|
./full_match/1/0x2b246A379e5f48d391f33ea4910ac2258426E6ae/sources/@nefty/base-contracts/contracts/ERC721ABase.sol
|
See ERC165: https://eips.ethereum.org/EIPS/eip-165
|
function supportsInterface(
bytes4 interfaceId
) public view virtual override(ERC721A, IERC165) returns (bool) {
return
}
| 5,011,876
|
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* @title EternalStorage
* @dev An ownable contract that can be used as a storage where the variables
* are stored in a set of mappings indexed by hash names.
* Contract importing following the guidelines in the zeppelinos upgreadability
* contracts post:
* https://github.com/zeppelinos/labs/tree/ff479995ed90c4dbb5e32294fa95b16a22bb99c8/upgradeability_using_eternal_storage
*
*/
contract EternalStorage is Ownable {
struct Storage {
mapping(bytes32 => bytes) _bytes;
mapping(bytes32 => bool) _bool;
mapping(bytes32 => int) _int;
mapping(bytes32 => uint256) _uint;
mapping(bytes32 => address) _address;
mapping(bytes32 => string) _string;
}
Storage internal s;
/**
* @dev The constructor sets the original `owner` of the
* contract to the sender account.
*/
constructor() public {
Ownable(msg.sender);
}
/**
* @dev Allows the owner to set a value for a boolean variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setBoolean(bytes32 h, bool v) external onlyOwner {
s._bool[h] = v;
}
/**
* @dev Allows the owner to set a value for a int variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setInt(bytes32 h, int v) external onlyOwner {
s._int[h] = v;
}
/**
* @dev Allows the owner to set a value for a boolean variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setUint(bytes32 h, uint256 v) external onlyOwner {
s._uint[h] = v;
}
/**
* @dev Allows the owner to set a value for a address variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setAddress(bytes32 h, address v) external onlyOwner {
s._address[h] = v;
}
/**
* @dev Allows the owner to set a value for a string variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setString(bytes32 h, string memory v) public onlyOwner {
s._string[h] = v;
}
/**
* @dev Allows the owner to set a value for a bytes variable.
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function setBytes(bytes32 h, bytes memory v) public onlyOwner {
s._bytes[h] = v;
}
/**
* @dev Get the value stored of a boolean variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getBoolean(bytes32 h) external view onlyOwner returns (bool){
return s._bool[h];
}
/**
* @dev Get the value stored of a int variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getInt(bytes32 h) external view onlyOwner returns (int){
return s._int[h];
}
/**
* @dev Get the value stored of a uint variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getUint(bytes32 h) external view onlyOwner returns (uint256){
return s._uint[h];
}
/**
* @dev Get the value stored of a address variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getAddress(bytes32 h) external view onlyOwner returns (address){
return s._address[h];
}
/**
* @dev Get the value stored of a string variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getString(bytes32 h) external view onlyOwner returns (string memory){
return s._string[h];
}
/**
* @dev Get the value stored of a bytes variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getBytes(bytes32 h) external view onlyOwner returns (bytes memory){
return s._bytes[h];
}
/**** Delete Methods ***********/
/// @param _key The key for the record
function deleteAddress(bytes32 _key) external onlyOwner {
delete s._address[_key];
}
/// @param _key The key for the record
function deleteUint(bytes32 _key) external onlyOwner {
delete s._uint[_key];
}
/// @param _key The key for the record
function deleteString(bytes32 _key) external onlyOwner {
delete s._string[_key];
}
/// @param _key The key for the record
function deleteBytes(bytes32 _key) external onlyOwner {
delete s._bytes[_key];
}
/// @param _key The key for the record
function deleteBool(bytes32 _key) external onlyOwner {
delete s._bool[_key];
}
/// @param _key The key for the record
function deleteInt(bytes32 _key) external onlyOwner {
delete s._int[_key];
}
}
|
_key The key for the record
|
function deleteString(bytes32 _key) external onlyOwner {
delete s._string[_key];
}
| 12,731,456
|
./full_match/1/0x649fb0a21A70701f34Dc2eceC790EE3851E3722e/sources/src/strategies/WethStrategyConvexStEth.sol
|
approve swap rewards to WETH
|
function _approveSwap() internal {
uint8 length = uint8(rewards.length);
for (uint8 i = 0; i < length; ++i) {
rewards[i].safeApprove(address(swap), type(uint256).max);
}
}
| 8,305,906
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./OracleGetter.sol";
import "./ERC20.sol";
import "./Inflation.sol";
import "hardhat/console.sol";
/**
@author Tellor Inc.
@title Chorus
@dev Chorus is a structure for issuing semi-stablecoins as community currencies
**/
// slither-disable-next-line missing-inheritance
contract Chorus is Inflation, OracleGetter, ERC20 {
/*Events*/
event CollateralThreshold(uint256 _collateralThreshold);//emits if collateral threshold changes
event CollateralPriceAge(uint256 _collateralPriceAge);//emits if collateral price age changes
event Liquidate(
address _party,
uint256 _tokensAmnt,
uint256 _collateralAmnt,
uint256 _collateralPenalty
);//emits upon a liquidation
event LiquidationPenatly(uint256 _newPenalty);//emits when the liquidation penalty changes
event MintTokens(
address _holder,
uint256 _amount,
address _to,
uint256 _collateralRatio
);//emits when new tokens are minted
event NewAdmin(address _newAdmin);//emits when a new admin is set
event WithdrawCollateral(
address _holder,
uint256 _collateralAmnt,
uint256 _collateralRatio
);//emits when collateral is withdrawn
event WithdrawToken(address _holder, uint256 _tokenAmnt, uint256 _collateralAmnt);//emits when tokens are withdrawn
event WithdrawTokenRequest(address _user, uint256 _amount);
/*Variables*/
struct WithdrawDetails{
uint256 amount;
uint256 requestDate;
}
ERC20 public collateralToken;
address public admin = msg.sender;
uint256 private tknPrice = 1e18;
uint256 public collateralID; // The collateral id used to check the Tellor oracle for its USD price.
uint256 public collateralPriceGranularity; //usually 1000000 in the Tellor system
uint256 public collateralThreshold = 15e17; // 150%.
uint256 public collateralPriceAge = 3600; // e.g. 1hr. This is the delay in the feed from Tellor
uint256 public liquidationPenatly = 0;
uint256 public inflRatePerSec;// The rate at which the token decreases value. 1e18 precision. 100e18 is 100%.
uint256 public inflLastUpdate = block.timestamp;
address public inflBeneficiary; // Where to send the inflation tokens.
mapping(address => WithdrawDetails) withdrawRequested;
/*Modifiers*/
modifier onlyAdmin {
require(msg.sender == admin, "not an admin");
_;
}
modifier within100e18Range(uint256 _value) {
require(_value > 0 && _value < 100e18, "value not within allowed limits");
_;
}
/*Functions*/
/**
* @dev This is the constructor, sets the inital paramaters in the system
* The parameters include, the Tellor Address, collateral token's address,
* collateral token's requestID, the price granualrity, the token name,
* token's symbol, inflation rate per year, and the inflation beneficiary
*/
constructor(
address payable _tellorAddress,
address _collateralToken,
uint256 _collateralID,
uint256 _collateralPriceGranularity,
string memory _tokenName,
string memory _tokenSymbol,
uint256 _inflRatePerYear,
address _inflBeneficiary,
bool _isWhitelisted
)
OracleGetter(_tellorAddress)
ERC20(_tokenName, _tokenSymbol,_isWhitelisted)
within100e18Range(_inflRatePerYear)
{
collateralID = _collateralID;
collateralToken = ERC20(_collateralToken);
collateralPriceGranularity = _collateralPriceGranularity;
require(_collateralPriceGranularity > 0 && _collateralPriceGranularity <= 1e18, "value not within allowed limits");
require(_inflBeneficiary != address(0), "benificiary address not set");
inflBeneficiary = _inflBeneficiary;
inflRatePerSec = yearlyRateToPerSec(_inflRatePerYear);
}
/**
* @dev Returns the current token price in USD reduced by the current inflation.
* @return uint256 token price
*/
function collateralBalance() external view returns (uint256) {
return collateralToken.balanceOf(address(this));
}
/**
* @dev Checks the Tellor oracle and gets the collateral price
* @return uint256 collateral price in USD upscaled to e18 precision.
*/
// slither-disable-next-line timestamp
function collateralPrice() public view returns (uint256) {
(bool _didGet, uint256 _collateralPrice, ) =
_getDataBefore(collateralID, block.timestamp - collateralPriceAge);
require(_didGet, "getting oracle price");
return mul(_collateralPrice, div(1e18, collateralPriceGranularity));
}
/**
* @dev A view funciton to look at the collateralization of the system
* @return uint256 collateral token balance of this address / totalSupply
*/
function collateralRatio() public view returns (uint256) {
uint256 _collateralBalance = collateralToken.balanceOf(address(this));
// slither-disable-next-line incorrect-equality
if(totalSupply() == 0 || _collateralBalance == 0) {
return 0;
}
uint256 _collateralValue = wmul(collateralPrice(), _collateralBalance);
uint256 tokenSupplyWithInflInterest =
accrueInterest(totalSupply(), inflRatePerSec, block.timestamp - inflLastUpdate);
uint256 _tokenValue = wmul(tokenPrice(), tokenSupplyWithInflInterest);
if(_tokenValue == 0){
return 100e18;
}
return wdiv(_collateralValue,_tokenValue);
}
/**
* @dev Allows the admin to deposit collateral
* @param _amount the amount of collateral token to deposit
*/
function depositCollateral(uint256 _amount) external onlyAdmin {
require(_amount > 0, "deposit amount 0");
require(
collateralToken.transferFrom(msg.sender, address(this), _amount),
"failed collateral deposit transfer"
);
}
/**
* @dev Function to allow anyone to liquidate the system if it is undercollateralized
*/
function liquidate() external {
require(
collateralRatio() < collateralThreshold,
"collateral utilizatoin is above threshold"
);
require(balanceOf(msg.sender) > 0, "msg sender doesn't own any tokens");
uint256 _tknSuplyRatio =
wdiv(collateralToken.balanceOf(address(this)), totalSupply());
uint256 _tokensToBurn = balanceOf(msg.sender);
uint256 _collatAmt = wmul(_tokensToBurn, _tknSuplyRatio);
uint256 _collatPenalty = wmul(_collatAmt, liquidationPenatly);
emit Liquidate(msg.sender, _tokensToBurn, _collatAmt, _collatPenalty);
_burn(msg.sender, _tokensToBurn);
require(
collateralToken.transfer(msg.sender, sub(_collatAmt, _collatPenalty)),
"collateral liquidation transfer fails"
);
require(
collateralToken.transfer(inflBeneficiary, _collatPenalty),
"collateral liquidation penalty transfer fails"
);
}
/**
* @dev Allows the admin to mint tokens up to the collateral threshold
* @param _amount the amount of collateral tokens to mint
* @param _to the address to mint them to;
*/
function mintToken(uint256 _amount, address _to) external onlyAdmin {
_mint(_to, _amount);
uint256 _cRatio = collateralRatio();
require(
_cRatio >= collateralThreshold,
"collateral utilization below the threshold"
);
emit MintTokens(msg.sender, _amount, _to, _cRatio);
}
/**
* @dev Allows a user to request to withdraw tokens
* @param _amount the amount of tokens to withdraw
*/
function requestWithdrawToken(uint256 _amount) external {
require(_amount > 0, "amount should be greater than 0");
require(balanceOf(msg.sender) >= _amount, "not enough balance");
withdrawRequested[msg.sender].requestDate = block.timestamp;
withdrawRequested[msg.sender].amount = _amount;
_transfer(msg.sender, address(this), _amount);
emit WithdrawTokenRequest(msg.sender, _amount);
}
/**
* @dev Allows the user to set a new admin address
* @param _newAdmin the address of the new admin address
*/
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0), "cannot send to the zero address");
admin = _newAdmin;
emit NewAdmin(_newAdmin);
}
/**
* @dev Allows the admin to set the collateral price Age (delay in feed from Tellor)
* @param _amount the amount of delay in the price feed (we want to wait for disputes)
*/
function setCollateralPriceAge(uint256 _amount) external onlyAdmin {
collateralPriceAge = _amount;
emit CollateralPriceAge(_amount);
}
/**
* @dev Allows the admin to set the Collateral threshold
* @param _amount new collateral threshold
*/
function setCollateralThreshold(uint256 _amount)
external
onlyAdmin
within100e18Range(_amount)
{
collateralThreshold = _amount;
emit CollateralThreshold(_amount);
}
/**
* @dev Allows the admin to set the liquidation penalty
* @param _amount the amount of the liquidation penalty
*/
function setLiquidationPenatly(uint256 _amount)
external
onlyAdmin
within100e18Range(_amount)
{
liquidationPenatly = wdiv(_amount, 100e18); // Convert to a fraction.
emit LiquidationPenatly(liquidationPenatly);
}
/**
* @dev Returns the current token price in USD reduced by the current inflation.
* @return uint256 token price
*/
function tokenPrice() public view returns (uint256) {
return
accrueInflation(
tknPrice,
inflRatePerSec,
block.timestamp - inflLastUpdate
);
}
/**
* @dev Function to reduce token price by the inflation rate,
* increases the total supply by the inflation rate and
* sends the new tokens to the inflation beneficiary.
*/
// slither-disable-next-line timestamp
function updateInflation() external {
uint256 secsPassed = block.timestamp - inflLastUpdate;
require(secsPassed > 0, "no inflation increase yet");
inflLastUpdate = block.timestamp;
tknPrice = accrueInflation(tknPrice, inflRatePerSec, secsPassed);
uint256 _tokensToMint =
sub(
accrueInterest(totalSupply(), inflRatePerSec, secsPassed),
totalSupply()
);
_mint(inflBeneficiary, _tokensToMint);
}
/**
* @dev Allows the admin to withdraw collateral above the threshold
* @param _amount the amount of collateral token to deposit
*/
function withdrawCollateral(uint256 _amount) external onlyAdmin {
require(
collateralToken.transfer(msg.sender, _amount),
"collateral transfer fails"
);
uint256 _cRatio = collateralRatio();
require(
_cRatio >= collateralThreshold,
"collateral utilization below the threshold"
);
// slither-disable-next-line reentrancy-events
emit WithdrawCollateral(msg.sender, _amount, _cRatio);
}
/**
* @dev Allows a user to withdraw tokens
*/
function withdrawToken() external {
WithdrawDetails memory wd = withdrawRequested[msg.sender];
uint256 _amount = withdrawRequested[msg.sender].amount;
require(_amount > 0, "amount should be greater than 0");
uint256 _waitPeriod = 1 + 100 * _amount / totalSupply() / 5; //increases by 1 day for every 5 percent
// slither-disable-next-line timestamp
require(block.timestamp - wd.requestDate >= 86400 * _waitPeriod, "must wait to withdraw");
withdrawRequested[msg.sender].amount = 0;
uint256 _collatPrice = collateralPrice();
uint256 _priceRatio = wdiv(tokenPrice(), _collatPrice);
uint256 _collateralAmnt = wmul(_priceRatio, _amount);
_burn(address(this), _amount);
require(
collateralToken.transfer(msg.sender, _collateralAmnt),
"collateral transfer fail"
);
// slither-disable-next-line reentrancy-events
emit WithdrawToken(msg.sender, _amount, _collateralAmnt);
}
}
|
Allows the user to set a new admin address _newAdmin the address of the new admin address/
|
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0), "cannot send to the zero address");
admin = _newAdmin;
emit NewAdmin(_newAdmin);
}
| 6,418,383
|
./full_match/137/0xC201fC7147daBbCaE388F20990f5cFa1fe322010/sources/contracts/Bet.sol
|
Assigns caller as bettor/
|
function addBettor() external payable {
_bet(true, msg.value);
}
| 4,666,642
|
./full_match/80001/0x1edb10fE0e4dd752EE7b935bDEBc7c5496DF5724/sources/wTFC_flat.sol
|
Sets the stored oracle and LINK token contracts with the addresses resolved by ENS Accounts for subnodes having different resolvers ensAddress The address of the ENS contract node The ENS node hash/
|
function useChainlinkWithENS(
address ensAddress,
bytes32 node
)
internal
{
ens = ENSInterface(ensAddress);
ensNode = node;
bytes32 linkSubnode = keccak256(abi.encodePacked(ensNode, ENS_TOKEN_SUBNAME));
ENSResolver_Chainlink resolver = ENSResolver_Chainlink(ens.resolver(linkSubnode));
setChainlinkToken(resolver.addr(linkSubnode));
updateChainlinkOracleWithENS();
}
| 5,642,589
|
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/OrderFulfiller.sol
|
Internal function to transfer each item contained in a given single order fulfillment after applying a respective fraction to the amount being transferred. orderParameters The parameters for the fulfilled order. numerator A value indicating the portion of the order that should be filled. denominator A value indicating the total order size. fulfillerConduitKey A bytes32 value indicating what conduit, if any, to source the fulfiller's token approvals from. The zero hash signifies that no conduit should be used, with direct approvals set on Consideration. recipient The intended recipient for all received items./ Read start time & end time from order parameters and place on stack. Initialize an accumulator array. From this point forward, no new memory regions can be safely allocated until the accumulator is no longer being utilized, as the accumulator operates in an open-ended fashion from this memory pointer; existing memory may still be accessed and modified, however. As of solidity 0.6.0, inline assembly cannot directly access function definitions, but can still access locally scoped function variables. This means that a local variable to reference the internal function definition (using the same type), along with a local variable with the desired type, must first be created. Then, the original function pointer can be recast to the desired type. Declare a nested scope to minimize stack depth. Read offer array length from memory and place on stack. Create a variable to indicate whether the order has any native offer items Iterate over each offer on the order. Skip overflow check as for loop is indexed starting at zero. Retrieve the offer item. Offer items for the native token can not be received outside of a match order function except as part of a contract order. Declare an additional nested scope to minimize stack depth. Apply fill fraction to get offer item amount to transfer. Utilize assembly to set overloaded offerItem arguments. Write new fractional amount to startAmount as amount. Write recipient to endAmount. If a non-contract order has native offer items, throw with an `InvalidNativeOfferItem` custom error. Note that this check requires that there are no order types beyond the current set (0-4). It will need to be modified if more order types are added. Declare a nested scope to minimize stack depth. Read consideration array length from memory and place on stack. Iterate over each consideration item on the order. Skip overflow check as for loop is indexed starting at zero. Retrieve the consideration item. Apply fraction & derive considerationItem amount to transfer. Use assembly to set overloaded considerationItem arguments. Write derived fractional amount to startAmount as amount. Write original recipient to endAmount as recipient. Reduce available value if offer spent ETH or a native token. Get the current available balance of native tokens. Ensure that sufficient native tokens are still available. Determine whether any native token balance remains. Return any remaining native token balance to the caller.
|
function _applyFractionsAndTransferEach(
OrderParameters memory orderParameters,
uint256 numerator,
uint256 denominator,
bytes32 fulfillerConduitKey,
address recipient
) internal {
uint256 startTime = orderParameters.startTime;
uint256 endTime = orderParameters.endTime;
bytes memory accumulator = new bytes(AccumulatorDisarmed);
unchecked {
uint256 totalOfferItems = orderParameters.offer.length;
uint256 anyNativeItems;
for (uint256 i = 0; i < totalOfferItems; ++i) {
OfferItem memory offerItem = orderParameters.offer[i];
{
ItemType itemType = offerItem.itemType;
assembly {
anyNativeItems := or(anyNativeItems, iszero(itemType))
}
}
{
uint256 amount = _applyFraction(
offerItem.startAmount,
offerItem.endAmount,
numerator,
denominator,
startTime,
endTime,
false
);
assembly {
mstore(
add(offerItem, ReceivedItem_amount_offset),
amount
)
mstore(
add(offerItem, ReceivedItem_recipient_offset),
recipient
)
}
}
offerItem,
orderParameters.offerer,
orderParameters.conduitKey,
accumulator
);
}
{
OrderType orderType = orderParameters.orderType;
uint256 invalidNativeOfferItem;
assembly {
invalidNativeOfferItem := and(
lt(orderType, 4),
anyNativeItems
)
}
if (invalidNativeOfferItem != 0) {
_revertInvalidNativeOfferItem();
}
}
}
unchecked {
uint256 totalConsiderationItems = orderParameters
.consideration
.length;
for (uint256 i = 0; i < totalConsiderationItems; ++i) {
ConsiderationItem memory considerationItem = (
orderParameters.consideration[i]
);
uint256 amount = _applyFraction(
considerationItem.startAmount,
considerationItem.endAmount,
numerator,
denominator,
startTime,
endTime,
true
);
assembly {
mstore(
add(considerationItem, ReceivedItem_amount_offset),
amount
)
mstore(
add(considerationItem, ReceivedItem_recipient_offset),
mload(
add(
considerationItem,
ConsiderationItem_recipient_offset
)
)
)
}
if (considerationItem.itemType == ItemType.NATIVE) {
assembly {
nativeTokenBalance := selfbalance()
}
if (amount > nativeTokenBalance) {
_revertInsufficientNativeTokensSupplied();
}
}
considerationItem,
msg.sender,
fulfillerConduitKey,
accumulator
);
}
}
assembly {
nativeTokenBalance := selfbalance()
}
if (nativeTokenBalance != 0) {
_transferNativeTokens(payable(msg.sender), nativeTokenBalance);
}
}
| 4,301,816
|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "../token/ERC721/extensions/ERC721Enumerable.sol";
import "../token/ERC721/extensions/ERC721URIStorage.sol";
import "../access/AccessControlEnumerable.sol";
import "../token/ERC20/IERC20.sol";
import "../utils/introspection/ERC2981.sol";
contract Tatum721ProvenanceWithRoyaltyUpdate is
ERC721Enumerable,
ERC2981,
ERC721URIStorage,
AccessControlEnumerable
{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant ROYALTY_UPDATER_ROLE = keccak256("ROYALTY_UPDATER_ROLE");
mapping(uint256 => string[]) private _tokenData;
mapping(uint256 => address[]) private _cashbackRecipients;
mapping(uint256 => uint256[]) private _cashbackValues;
mapping(uint256 => uint256[]) private _fixedValues;
mapping(uint256 => address) private _customToken;
bool _publicMint;
event TransferWithProvenance(
uint256 indexed id,
address owner,
string data,
uint256 value
);
constructor(string memory name_, string memory symbol_, bool publicMint)
ERC721(name_, symbol_)
{
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_publicMint = publicMint;
}
function royaltyInfo(uint256 tokenId, uint256 value)
external
view
override
returns (address, uint256)
{
uint256 result;
uint256 cbvalue = (_cashbackValues[tokenId][0] * value) / 10000;
result = _cashbackCalculator(cbvalue, _fixedValues[tokenId][0]);
return (_cashbackRecipients[tokenId][0], result);
}
function _appendTokenData(uint256 tokenId, string calldata tokenData)
internal
virtual
{
require(
_exists(tokenId),
"ERC721URIStorage: URI set of nonexistent token"
);
_tokenData[tokenId].push(tokenData);
}
function mintWithTokenURI(
address to,
uint256 tokenId,
string memory uri,
address[] memory recipientAddresses,
uint256[] memory cashbackValues,
uint256[] memory fValues,
address erc20
) public {
require(
erc20 != address(0),
"Custom cashbacks cannot be set to 0 address"
);
_customToken[tokenId] = erc20;
return
mintWithTokenURI(
to,
tokenId,
uri,
recipientAddresses,
cashbackValues,
fValues
);
}
function mintWithTokenURI(
address to,
uint256 tokenId,
string memory uri,
address[] memory recipientAddresses,
uint256[] memory cashbackValues,
uint256[] memory fValues
) public {
if (!_publicMint) {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC721PresetMinterPauserAutoId: must have minter role to mint"
);
}
_mint(to, tokenId);
_setTokenURI(tokenId, uri);
// saving cashback addresses and values
if (recipientAddresses.length > 0) {
_cashbackRecipients[tokenId] = recipientAddresses;
_cashbackValues[tokenId] = cashbackValues;
_fixedValues[tokenId] = fValues;
}
}
function mintMultiple(
address[] memory to,
uint256[] memory tokenId,
string[] memory uri,
address[][] memory recipientAddresses,
uint256[][] memory cashbackValues,
uint256[][] memory fValues,
address erc20
) public {
require(
erc20 != address(0),
"Custom cashbacks cannot be set to 0 address"
);
for (uint256 i; i < to.length; i++) {
_customToken[tokenId[i]] = erc20;
}
return
mintMultiple(
to,
tokenId,
uri,
recipientAddresses,
cashbackValues,
fValues
);
}
function mintMultiple(
address[] memory to,
uint256[] memory tokenId,
string[] memory uri,
address[][] memory recipientAddresses,
uint256[][] memory cashbackValues,
uint256[][] memory fValues
) public {
if (!_publicMint) {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC721PresetMinterPauserAutoId: must have minter role to mint"
);
}
for (uint256 i; i < to.length; i++) {
_mint(to[i], tokenId[i]);
_setTokenURI(tokenId[i], uri[i]);
if (
recipientAddresses.length > 0 &&
recipientAddresses[i].length > 0
) {
_cashbackRecipients[tokenId[i]] = recipientAddresses[i];
_cashbackValues[tokenId[i]] = cashbackValues[i];
_fixedValues[tokenId[i]] = fValues[i];
}
}
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC721, ERC721Enumerable, ERC2981)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function tokenURI(uint256 tokenId)
public
view
virtual
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return ERC721URIStorage.tokenURI(tokenId);
}
function getCashbackAddress(uint256 tokenId)
public
view
virtual
returns (address)
{
return _customToken[tokenId];
}
function getTokenData(uint256 tokenId)
public
view
virtual
returns (string[] memory)
{
return _tokenData[tokenId];
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId)
internal
virtual
override(ERC721, ERC721URIStorage)
{
return ERC721URIStorage._burn(tokenId);
}
function tokenCashbackValues(uint256 tokenId, uint256 tokenPrice)
public
view
virtual
returns (uint256[] memory)
{
uint256[] memory result = _cashbackValues[tokenId];
for (uint i = 0; i < result.length; i++) {
uint256 cbvalue = (result[i] * tokenPrice) / 10000;
result[i] = _cashbackCalculator(cbvalue, _fixedValues[tokenId][i]);
}
return result;
}
function tokenCashbackRecipients(uint256 tokenId)
public
view
virtual
returns (address[] memory)
{
return _cashbackRecipients[tokenId];
}
function updateCashbackForAuthor(uint256 tokenId, uint256 cashbackValue)
public
{
for (uint256 i; i < _cashbackValues[tokenId].length; i++) {
if (_cashbackRecipients[tokenId][i] == _msgSender()) {
_cashbackValues[tokenId][i] = cashbackValue;
}
}
}
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Burnable: caller is not owner nor approved"
);
_burn(tokenId);
}
function _stringToUint(string memory s)
internal
pure
returns (uint256 result)
{
bytes memory b = bytes(s);
// result = 0;
for (uint256 i; i < b.length; i++) {
uint256 c = uint256(uint8(b[i]));
if (c >= 48 && c <= 57) {
result = result * 10 + (c - 48);
}
}
}
function allowance(address a, uint256 t) public view returns (bool) {
return _isApprovedOrOwner(a, t);
}
function safeTransfer(
address to,
uint256 tokenId,
bytes calldata dataBytes
) public payable {
uint256 index;
uint256 value;
uint256 percentSum;
IERC20 token;
(index, value) = _bytesCheck(dataBytes);
if (_customToken[tokenId] != address(0)) {
token = IERC20(_customToken[tokenId]);
}
if (_cashbackRecipients[tokenId].length > 0) {
for (uint256 i = 0; i < _cashbackValues[tokenId].length; i++) {
uint256 iPercent = (_cashbackValues[tokenId][i] * value) /
10000;
if (iPercent >= _fixedValues[tokenId][i]) {
percentSum += iPercent;
} else {
percentSum += _fixedValues[tokenId][i];
}
}
if (_customToken[tokenId] == address(0)) {
if (percentSum > msg.value) {
payable(msg.sender).transfer(msg.value);
revert(
"Value should be greater than or equal to cashback value"
);
}
} else {
if (percentSum > token.allowance(to, address(this))) {
revert(
"Insufficient ERC20 allowance balance for paying for the asset."
);
}
}
for (uint256 i = 0; i < _cashbackRecipients[tokenId].length; i++) {
// transferring cashback to authors
uint256 cbvalue = (_cashbackValues[tokenId][i] * value) / 10000;
if (_customToken[tokenId] == address(0)) {
cbvalue = _cashbackCalculator(
cbvalue,
_fixedValues[tokenId][i]
);
payable(_cashbackRecipients[tokenId][i]).transfer(cbvalue);
} else {
cbvalue = _cashbackCalculator(
cbvalue,
_fixedValues[tokenId][i]
);
token.transferFrom(
to,
_cashbackRecipients[tokenId][i],
cbvalue
);
}
}
if (_customToken[tokenId] == address(0) && msg.value > percentSum) {
payable(msg.sender).transfer(msg.value - percentSum);
}
if (_customToken[tokenId] != address(0) && msg.value > 0) {
payable(msg.sender).transfer(msg.value);
}
}
_safeTransfer(msg.sender, to, tokenId, dataBytes);
string calldata dataString = string(dataBytes);
_appendTokenData(tokenId, dataString);
emit TransferWithProvenance(tokenId, to, dataString[: index], value);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata dataBytes
) public payable virtual override {
uint256 index;
uint256 value;
uint256 percentSum;
IERC20 token;
(index, value) = _bytesCheck(dataBytes);
if (_customToken[tokenId] != address(0)) {
token = IERC20(_customToken[tokenId]);
}
if (_cashbackRecipients[tokenId].length > 0) {
for (uint256 i = 0; i < _cashbackValues[tokenId].length; i++) {
uint256 iPercent = (_cashbackValues[tokenId][i] * value) /
10000;
if (iPercent >= _fixedValues[tokenId][i]) {
percentSum += iPercent;
} else {
percentSum += _fixedValues[tokenId][i];
}
}
if (_customToken[tokenId] == address(0)) {
if (percentSum > msg.value) {
payable(from).transfer(msg.value);
revert(
"Value should be greater than or equal to cashback value"
);
}
} else {
if (percentSum > token.allowance(to, address(this))) {
revert(
"Insufficient ERC20 allowance balance for paying for the asset."
);
}
}
for (uint256 i = 0; i < _cashbackRecipients[tokenId].length; i++) {
// transferring cashback to authors
uint256 cbvalue = (_cashbackValues[tokenId][i] * value) / 10000;
if (_customToken[tokenId] == address(0)) {
cbvalue = _cashbackCalculator(
cbvalue,
_fixedValues[tokenId][i]
);
payable(_cashbackRecipients[tokenId][i]).transfer(cbvalue);
} else {
cbvalue = _cashbackCalculator(
cbvalue,
_fixedValues[tokenId][i]
);
token.transferFrom(
to,
_cashbackRecipients[tokenId][i],
cbvalue
);
}
}
if (_customToken[tokenId] != address(0) && msg.value > 0) {
payable(from).transfer(msg.value);
}
if (_customToken[tokenId] == address(0) && msg.value > percentSum) {
payable(from).transfer(msg.value - percentSum);
}
}
_safeTransfer(from, to, tokenId, dataBytes);
string calldata dataString = string(dataBytes);
_appendTokenData(tokenId, dataString);
emit TransferWithProvenance(tokenId, to, dataString[: index], value);
}
function _cashbackCalculator(uint256 x, uint256 y)
private
pure
returns (uint256)
{
if (x >= y) {
return x;
}
return y;
}
function _bytesCheck(bytes calldata dataBytes)
private
pure
returns (uint256 index, uint256 value)
{
for (uint256 i = 0; i < dataBytes.length; i++) {
if (
dataBytes[i] == 0x27 &&
dataBytes.length > i + 8 &&
dataBytes[i + 1] == 0x27 &&
dataBytes[i + 2] == 0x27 &&
dataBytes[i + 3] == 0x23 &&
dataBytes[i + 4] == 0x23 &&
dataBytes[i + 5] == 0x23 &&
dataBytes[i + 6] == 0x27 &&
dataBytes[i + 7] == 0x27 &&
dataBytes[i + 8] == 0x27
) {
index = i;
bytes calldata valueBytes = dataBytes[index + 9 :];
value = _stringToUint(string(valueBytes));
}
}
}
}
|
transferring cashback to authors
|
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata dataBytes
) public payable virtual override {
uint256 index;
uint256 value;
uint256 percentSum;
IERC20 token;
(index, value) = _bytesCheck(dataBytes);
if (_customToken[tokenId] != address(0)) {
token = IERC20(_customToken[tokenId]);
}
if (_cashbackRecipients[tokenId].length > 0) {
for (uint256 i = 0; i < _cashbackValues[tokenId].length; i++) {
uint256 iPercent = (_cashbackValues[tokenId][i] * value) /
10000;
if (iPercent >= _fixedValues[tokenId][i]) {
percentSum += iPercent;
percentSum += _fixedValues[tokenId][i];
}
}
if (_customToken[tokenId] == address(0)) {
if (percentSum > msg.value) {
payable(from).transfer(msg.value);
revert(
"Value should be greater than or equal to cashback value"
);
}
if (percentSum > token.allowance(to, address(this))) {
revert(
"Insufficient ERC20 allowance balance for paying for the asset."
);
}
}
for (uint256 i = 0; i < _cashbackRecipients[tokenId].length; i++) {
uint256 cbvalue = (_cashbackValues[tokenId][i] * value) / 10000;
if (_customToken[tokenId] == address(0)) {
cbvalue = _cashbackCalculator(
cbvalue,
_fixedValues[tokenId][i]
);
payable(_cashbackRecipients[tokenId][i]).transfer(cbvalue);
cbvalue = _cashbackCalculator(
cbvalue,
_fixedValues[tokenId][i]
);
token.transferFrom(
to,
_cashbackRecipients[tokenId][i],
cbvalue
);
}
}
if (_customToken[tokenId] != address(0) && msg.value > 0) {
payable(from).transfer(msg.value);
}
if (_customToken[tokenId] == address(0) && msg.value > percentSum) {
payable(from).transfer(msg.value - percentSum);
}
}
_safeTransfer(from, to, tokenId, dataBytes);
string calldata dataString = string(dataBytes);
_appendTokenData(tokenId, dataString);
emit TransferWithProvenance(tokenId, to, dataString[: index], value);
}
| 940,595
|
./partial_match/1/0x7721aC9C664a7284b1c6deF0381669Af62906c01/sources/DMGYieldFarmingV2.sol
|
Admin Events User Events Admin Functions User Functions Misc Functions
|
interface IDMGYieldFarmingV2 {
event GlobalProxySet(address indexed proxy, bool isTrusted);
event TokenAdded(address indexed token, address indexed underlyingToken, uint8 underlyingTokenDecimals, uint16 points, uint16 fees);
event TokenRemoved(address indexed token);
event FarmSeasonBegun(uint indexed seasonIndex, uint dmgAmount);
event FarmSeasonExtended(uint indexed seasonIndex, uint dmgAmount);
event FarmSeasonEnd(uint indexed seasonIndex, address dustRecipient, uint dustyDmgAmount);
event DmgGrowthCoefficientSet(uint coefficient);
event RewardPointsSet(address indexed token, uint16 points);
event UnderlyingTokenValuatorChanged(address newUnderlyingTokenValutor, address oldUnderlyingTokenValutor);
event UniswapV2RouterChanged(address newUniswapV2Router, address oldUniswapV2Router);
event FeesChanged(address indexed token, uint16 feeAmount);
event TokenTypeChanged(address indexed token, DMGYieldFarmingV2Lib.TokenType tokenType);
event Approval(address indexed user, address indexed spender, bool isTrusted);
event BeginFarming(address indexed owner, address indexed token, uint depositedAmount);
event EndFarming(address indexed owner, address indexed token, uint withdrawnAmount, uint earnedDmgAmount);
event WithdrawOutOfSeason(address indexed owner, address indexed token, address indexed recipient, uint amount);
event Harvest(address indexed owner, address indexed token, uint earnedDmgAmount);
event HarvestFeePaid(address indexed owner, address indexed token, uint tokenAmountToConvert, uint dmgAmountBurned);
function approveGloballyTrustedProxy(
address proxy,
bool isTrusted
) external;
function isGloballyTrustedProxy(
address proxy
) external view returns (bool);
function addAllowableToken(
address token,
address underlyingToken,
uint8 underlyingTokenDecimals,
uint16 points,
uint16 fees,
DMGYieldFarmingV2Lib.TokenType tokenType
) external;
function removeAllowableToken(
address token
) external;
function setRewardPointsByTokens(
address[] calldata tokens,
uint16[] calldata points
) external;
function setDmgGrowthCoefficient(
uint dmgGrowthCoefficient
) external;
function beginFarmingSeason(
uint dmgAmount
) external;
function addToFarmingSeason(
uint dmgAmount
) external;
function endActiveFarmingSeason(
address dustRecipient
) external;
function setUnderlyingTokenValuator(
address underlyingTokenValuator
) external;
function setWethToken(
address weth
) external;
function setUniswapV2Router(
address uniswapV2Router
) external;
function setFeesByTokens(
address[] calldata tokens,
uint16[] calldata fees
) external;
function setTokenTypeByToken(
address token,
DMGYieldFarmingV2Lib.TokenType tokenType
) external;
function initializeDmgBalance() external;
function approve(address spender, bool isTrusted) external;
function isApproved(
address user,
address spender
) external view returns (bool);
function beginFarming(
address user,
address funder,
address token,
uint amount
) external;
function endFarmingByToken(
address from,
address recipient,
address token
) external returns (uint, uint);
function endFarmingByTokenAndAmount(
address from,
address recipient,
address token,
uint amount
) external returns (uint, uint);
function withdrawAllWhenOutOfSeason(
address user,
address recipient
) external returns (address[] memory, uint[] memory);
function withdrawByTokenWhenOutOfSeason(
address user,
address recipient,
address token
) external returns (uint);
function getRewardBalanceByOwner(
address owner
) external view returns (uint);
function getRewardBalanceByOwnerAndToken(
address owner,
address token
) external view returns (uint);
function balanceOf(
address owner,
address token
) external view returns (uint);
function getMostRecentDepositTimestampByOwnerAndToken(
address owner,
address token
) external view returns (uint64);
function getMostRecentIndexedDmgEarnedByOwnerAndToken(
address owner,
address token
) external view returns (uint);
function harvestDmgByUserAndToken(
address user,
address recipient,
address token
) external returns (uint);
function harvestDmgByUser(
address user,
address recipient
) external returns (uint);
function getUnderlyingTokenByFarmToken(
address farmToken
) external view returns (address);
function getFarmTokens() external view returns (address[] memory);
function isSupportedToken(address token) external view returns (bool);
function isFarmActive() external view returns (bool);
function dmmController() external view returns (address);
function guardian() external view returns (address);
function dmgToken() external view returns (address);
function dmgGrowthCoefficient() external view returns (uint);
function getRewardPointsByToken(address token) external view returns (uint16);
function getTokenDecimalsByToken(address token) external view returns (uint8);
function getTokenTypeByToken(address token) external view returns (DMGYieldFarmingV2Lib.TokenType);
function getTokenIndexPlusOneByToken(address token) external view returns (uint);
function underlyingTokenValuator() external view returns (address);
function weth() external view returns (address);
function uniswapV2Router() external view returns (address);
function getFeesByToken(address token) external view returns (uint16);
}
| 4,050,010
|
./full_match/5/0x939B84B4b4978B8A1e11A2AeC009d219217a1175/sources/project_/contracts/Factory/BXNFTFactory.sol
|
adding constructor arguments to BeaconProxy bytecode
|
function _getCreationBytecode(bytes memory data, tokenTypes tokenType)
internal
view
returns (bytes memory)
{
address beacon;
if(keccak256(abi.encodePacked(tokenType)) == keccak256(abi.encodePacked(tokenTypes.ERC721))){
beacon = erc721Beacon;
beacon = erc721ABeacon;
beacon = erc1155Beacon;
}
return abi.encodePacked(
type(BXBeaconProxy).creationCode, abi.encode(beacon,data)
);
}
| 1,950,908
|
//Address: 0x91a973bee89225c6c186419b5bab1944fc5736c7
//Contract name: LPVault
//Balance: 0 Ether
//Verification Date: 12/20/2017
//Transacion Count: 6
// CODE STARTS HERE
//File: node_modules/giveth-common-contracts/contracts/Owned.sol
pragma solidity ^0.4.15;
/// @title Owned
/// @author Adrià Massanet <adria@codecontext.io>
/// @notice The Owned contract has an owner address, and provides basic
/// authorization control functions, this simplifies & the implementation of
/// user permissions; this contract has three work flows for a change in
/// ownership, the first requires the new owner to validate that they have the
/// ability to accept ownership, the second allows the ownership to be
/// directly transfered without requiring acceptance, and the third allows for
/// the ownership to be removed to allow for decentralization
contract Owned {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed by, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event OwnershipRemoved();
/// @dev The constructor sets the `msg.sender` as the`owner` of the contract
function Owned() public {
owner = msg.sender;
}
/// @dev `owner` is the only address that can call a function with this
/// modifier
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
/// @dev In this 1st option for ownership transfer `proposeOwnership()` must
/// be called first by the current `owner` then `acceptOwnership()` must be
/// called by the `newOwnerCandidate`
/// @notice `onlyOwner` Proposes to transfer control of the contract to a
/// new owner
/// @param _newOwnerCandidate The address being proposed as the new owner
function proposeOwnership(address _newOwnerCandidate) public onlyOwner {
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @notice Can only be called by the `newOwnerCandidate`, accepts the
/// transfer of ownership
function acceptOwnership() public {
require(msg.sender == newOwnerCandidate);
address oldOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
/// @dev In this 2nd option for ownership transfer `changeOwnership()` can
/// be called and it will immediately assign ownership to the `newOwner`
/// @notice `owner` can step down and assign some other address to this role
/// @param _newOwner The address of the new owner
function changeOwnership(address _newOwner) public onlyOwner {
require(_newOwner != 0x0);
address oldOwner = owner;
owner = _newOwner;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
/// @dev In this 3rd option for ownership transfer `removeOwnership()` can
/// be called and it will immediately assign ownership to the 0x0 address;
/// it requires a 0xdece be input as a parameter to prevent accidental use
/// @notice Decentralizes the contract, this operation cannot be undone
/// @param _dac `0xdac` has to be entered for this function to work
function removeOwnership(address _dac) public onlyOwner {
require(_dac == 0xdac);
owner = 0x0;
newOwnerCandidate = 0x0;
OwnershipRemoved();
}
}
//File: node_modules/giveth-common-contracts/contracts/ERC20.sol
pragma solidity ^0.4.15;
/**
* @title ERC20
* @dev A standard interface for tokens.
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20 {
/// @dev Returns the total token supply
function totalSupply() public constant returns (uint256 supply);
/// @dev Returns the account balance of the account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
/// @dev Transfers _value number of tokens to address _to
function transfer(address _to, uint256 _value) public returns (bool success);
/// @dev Transfers _value number of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @dev Allows _spender to withdraw from the msg.sender's account up to the _value amount
function approve(address _spender, uint256 _value) public returns (bool success);
/// @dev Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
//File: node_modules/giveth-common-contracts/contracts/Escapable.sol
pragma solidity ^0.4.15;
/*
Copyright 2016, Jordi Baylina
Contributor: Adrià Massanet <adria@codecontext.io>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @dev `Escapable` is a base level contract built off of the `Owned`
/// contract; it creates an escape hatch function that can be called in an
/// emergency that will allow designated addresses to send any ether or tokens
/// held in the contract to an `escapeHatchDestination` as long as they were
/// not blacklisted
contract Escapable is Owned {
address public escapeHatchCaller;
address public escapeHatchDestination;
mapping (address=>bool) private escapeBlacklist; // Token contract addresses
/// @notice The Constructor assigns the `escapeHatchDestination` and the
/// `escapeHatchCaller`
/// @param _escapeHatchCaller The address of a trusted account or contract
/// to call `escapeHatch()` to send the ether in this contract to the
/// `escapeHatchDestination` it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
/// @param _escapeHatchDestination The address of a safe location (usu a
/// Multisig) to send the ether held in this contract; if a neutral address
/// is required, the WHG Multisig is an option:
/// 0x8Ff920020c8AD673661c8117f2855C384758C572
function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) public {
escapeHatchCaller = _escapeHatchCaller;
escapeHatchDestination = _escapeHatchDestination;
}
/// @dev The addresses preassigned as `escapeHatchCaller` or `owner`
/// are the only addresses that can call a function with this modifier
modifier onlyEscapeHatchCallerOrOwner {
require ((msg.sender == escapeHatchCaller)||(msg.sender == owner));
_;
}
/// @notice Creates the blacklist of tokens that are not able to be taken
/// out of the contract; can only be done at the deployment, and the logic
/// to add to the blacklist will be in the constructor of a child contract
/// @param _token the token contract address that is to be blacklisted
function blacklistEscapeToken(address _token) internal {
escapeBlacklist[_token] = true;
EscapeHatchBlackistedToken(_token);
}
/// @notice Checks to see if `_token` is in the blacklist of tokens
/// @param _token the token address being queried
/// @return False if `_token` is in the blacklist and can't be taken out of
/// the contract via the `escapeHatch()`
function isTokenEscapable(address _token) constant public returns (bool) {
return !escapeBlacklist[_token];
}
/// @notice The `escapeHatch()` should only be called as a last resort if a
/// security issue is uncovered or something unexpected happened
/// @param _token to transfer, use 0x0 for ether
function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner {
require(escapeBlacklist[_token]==false);
uint256 balance;
/// @dev Logic for ether
if (_token == 0x0) {
balance = this.balance;
escapeHatchDestination.transfer(balance);
EscapeHatchCalled(_token, balance);
return;
}
/// @dev Logic for tokens
ERC20 token = ERC20(_token);
balance = token.balanceOf(this);
require(token.transfer(escapeHatchDestination, balance));
EscapeHatchCalled(_token, balance);
}
/// @notice Changes the address assigned to call `escapeHatch()`
/// @param _newEscapeHatchCaller The address of a trusted account or
/// contract to call `escapeHatch()` to send the value in this contract to
/// the `escapeHatchDestination`; it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner {
escapeHatchCaller = _newEscapeHatchCaller;
}
event EscapeHatchBlackistedToken(address token);
event EscapeHatchCalled(address token, uint amount);
}
//File: contracts/LPVault.sol
pragma solidity ^0.4.11;
/*
Copyright 2017, Jordi Baylina
Contributors: RJ Ewing, Griff Green, Arthur Lunn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title LPVault
/// @author Jordi Baylina
/// @dev This contract holds ether securely for liquid pledging systems; for
/// this iteration the funds will come often be escaped to the Giveth Multisig
/// (safety precaution), but once fully tested and optimized this contract will
/// be a safe place to store funds equipped with optional variable time delays
/// to allow for an optional escapeHatch to be implemented in case of issues;
/// future versions of this contract will be enabled for tokens
/// @dev `LiquidPledging` is a basic interface to allow the `LPVault` contract
/// to confirm and cancel payments in the `LiquidPledging` contract.
contract LiquidPledging {
function confirmPayment(uint64 idPledge, uint amount) public;
function cancelPayment(uint64 idPledge, uint amount) public;
}
/// @dev `LPVault` is a higher level contract built off of the `Escapable`
/// contract that holds funds for the liquid pledging system.
contract LPVault is Escapable {
LiquidPledging public liquidPledging; // LiquidPledging contract's address
bool public autoPay; // If false, payments will take 2 txs to be completed
enum PaymentStatus {
Pending, // When the payment is awaiting confirmation
Paid, // When the payment has been sent
Canceled // When the payment will never be sent
}
/// @dev `Payment` is a public structure that describes the details of
/// each payment the `ref` param makes it easy to track the movements of
/// funds transparently by its connection to other `Payment` structs
struct Payment {
PaymentStatus state; // Pending, Paid or Canceled
bytes32 ref; // an input that references details from other contracts
address dest; // recipient of the ETH
uint amount; // amount of ETH (in wei) to be sent
}
// @dev An array that contains all the payments for this LPVault
Payment[] public payments;
function LPVault(address _escapeHatchCaller, address _escapeHatchDestination)
Escapable(_escapeHatchCaller, _escapeHatchDestination) public
{
}
/// @dev The attached `LiquidPledging` contract is the only address that can
/// call a function with this modifier
modifier onlyLiquidPledging() {
require(msg.sender == address(liquidPledging));
_;
}
/// @dev The fall back function allows ETH to be deposited into the LPVault
/// through a simple send
function () public payable {}
/// @notice `onlyOwner` used to attach a specific liquidPledging instance
/// to this LPvault; keep in mind that once a liquidPledging contract is
/// attached it cannot be undone, this vault will be forever connected
/// @param _newLiquidPledging A full liquid pledging contract
function setLiquidPledging(address _newLiquidPledging) public onlyOwner {
require(address(liquidPledging) == 0x0);
liquidPledging = LiquidPledging(_newLiquidPledging);
}
/// @notice Used to decentralize, toggles whether the LPVault will
/// automatically confirm a payment after the payment has been authorized
/// @param _automatic If true, payments will confirm instantly, if false
/// the training wheels are put on and the owner must manually approve
/// every payment
function setAutopay(bool _automatic) public onlyOwner {
autoPay = _automatic;
AutoPaySet();
}
/// @notice `onlyLiquidPledging` authorizes payments from this contract, if
/// `autoPay == true` the transfer happens automatically `else` the `owner`
/// must call `confirmPayment()` for a transfer to occur (training wheels);
/// either way, a new payment is added to `payments[]`
/// @param _ref References the payment will normally be the pledgeID
/// @param _dest The address that payments will be sent to
/// @param _amount The amount that the payment is being authorized for
/// @return idPayment The id of the payment (needed by the owner to confirm)
function authorizePayment(
bytes32 _ref,
address _dest,
uint _amount
) public onlyLiquidPledging returns (uint)
{
uint idPayment = payments.length;
payments.length ++;
payments[idPayment].state = PaymentStatus.Pending;
payments[idPayment].ref = _ref;
payments[idPayment].dest = _dest;
payments[idPayment].amount = _amount;
AuthorizePayment(idPayment, _ref, _dest, _amount);
if (autoPay) {
doConfirmPayment(idPayment);
}
return idPayment;
}
/// @notice Allows the owner to confirm payments; since
/// `authorizePayment` is the only way to populate the `payments[]` array
/// this is generally used when `autopay` is `false` after a payment has
/// has been authorized
/// @param _idPayment Array lookup for the payment.
function confirmPayment(uint _idPayment) public onlyOwner {
doConfirmPayment(_idPayment);
}
/// @notice Transfers ETH according to the data held within the specified
/// payment id (internal function)
/// @param _idPayment id number for the payment about to be fulfilled
function doConfirmPayment(uint _idPayment) internal {
require(_idPayment < payments.length);
Payment storage p = payments[_idPayment];
require(p.state == PaymentStatus.Pending);
p.state = PaymentStatus.Paid;
liquidPledging.confirmPayment(uint64(p.ref), p.amount);
p.dest.transfer(p.amount); // Transfers ETH denominated in wei
ConfirmPayment(_idPayment, p.ref);
}
/// @notice When `autopay` is `false` and after a payment has been authorized
/// to allow the owner to cancel a payment instead of confirming it.
/// @param _idPayment Array lookup for the payment.
function cancelPayment(uint _idPayment) public onlyOwner {
doCancelPayment(_idPayment);
}
/// @notice Cancels a pending payment (internal function)
/// @param _idPayment id number for the payment
function doCancelPayment(uint _idPayment) internal {
require(_idPayment < payments.length);
Payment storage p = payments[_idPayment];
require(p.state == PaymentStatus.Pending);
p.state = PaymentStatus.Canceled;
liquidPledging.cancelPayment(uint64(p.ref), p.amount);
CancelPayment(_idPayment, p.ref);
}
/// @notice `onlyOwner` An efficient way to confirm multiple payments
/// @param _idPayments An array of multiple payment ids
function multiConfirm(uint[] _idPayments) public onlyOwner {
for (uint i = 0; i < _idPayments.length; i++) {
doConfirmPayment(_idPayments[i]);
}
}
/// @notice `onlyOwner` An efficient way to cancel multiple payments
/// @param _idPayments An array of multiple payment ids
function multiCancel(uint[] _idPayments) public onlyOwner {
for (uint i = 0; i < _idPayments.length; i++) {
doCancelPayment(_idPayments[i]);
}
}
/// @return The total number of payments that have ever been authorized
function nPayments() constant public returns (uint) {
return payments.length;
}
/// Transfer eth or tokens to the escapeHatchDestination.
/// Used as a safety mechanism to prevent the vault from holding too much value
/// before being thoroughly battle-tested.
/// @param _token to transfer, use 0x0 for ether
/// @param _amount to transfer
function escapeFunds(address _token, uint _amount) public onlyOwner {
/// @dev Logic for ether
if (_token == 0x0) {
require(this.balance >= _amount);
escapeHatchDestination.transfer(_amount);
EscapeHatchCalled(_token, _amount);
return;
}
/// @dev Logic for tokens
ERC20 token = ERC20(_token);
uint balance = token.balanceOf(this);
require(balance >= _amount);
require(token.transfer(escapeHatchDestination, _amount));
EscapeFundsCalled(_token, _amount);
}
event AutoPaySet();
event EscapeFundsCalled(address token, uint amount);
event ConfirmPayment(uint indexed idPayment, bytes32 indexed ref);
event CancelPayment(uint indexed idPayment, bytes32 indexed ref);
event AuthorizePayment(
uint indexed idPayment,
bytes32 indexed ref,
address indexed dest,
uint amount
);
}
|
`onlyOwner` used to attach a specific liquidPledging instance to this LPvault; keep in mind that once a liquidPledging contract is attached it cannot be undone, this vault will be forever connected _newLiquidPledging A full liquid pledging contract
|
function setLiquidPledging(address _newLiquidPledging) public onlyOwner {
require(address(liquidPledging) == 0x0);
liquidPledging = LiquidPledging(_newLiquidPledging);
}
| 6,430,486
|
pragma solidity 0.5.16;
interface ierc207 { //inject NONSTANDARD NAMING
function TOTALSUPPLY3() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF6(address ACCOUNT8) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER0(address RECIPIENT4, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE8(address OWNER10, address SPENDER9) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE6(address SPENDER9, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM9(address SENDER7, address RECIPIENT4, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER10(address indexed FROM9, address indexed TO4, uint VALUE10); //inject NONSTANDARD NAMING
event APPROVAL6(address indexed OWNER10, address indexed SPENDER9, uint VALUE10); //inject NONSTANDARD NAMING
}
contract context1 { //inject NONSTANDARD NAMING
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER8() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract erc209 is context1, ierc207 { //inject NONSTANDARD NAMING
using safemath3 for uint;
mapping (address => uint) private _BALANCES7; //inject NONSTANDARD NAMING
mapping (address => mapping (address => uint)) private _ALLOWANCES5; //inject NONSTANDARD NAMING
uint private _TOTALSUPPLY10; //inject NONSTANDARD NAMING
function TOTALSUPPLY3() public view returns (uint) { //inject NONSTANDARD NAMING
return _TOTALSUPPLY10;
}
function BALANCEOF6(address ACCOUNT8) public view returns (uint) { //inject NONSTANDARD NAMING
return _BALANCES7[ACCOUNT8];
}
function TRANSFER0(address RECIPIENT4, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER10(_MSGSENDER8(), RECIPIENT4, AMOUNT10);
return true;
}
function ALLOWANCE8(address OWNER10, address SPENDER9) public view returns (uint) { //inject NONSTANDARD NAMING
return _ALLOWANCES5[OWNER10][SPENDER9];
}
function APPROVE6(address SPENDER9, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE9(_MSGSENDER8(), SPENDER9, AMOUNT10);
return true;
}
function TRANSFERFROM9(address SENDER7, address RECIPIENT4, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER10(SENDER7, RECIPIENT4, AMOUNT10);
_APPROVE9(SENDER7, _MSGSENDER8(), _ALLOWANCES5[SENDER7][_MSGSENDER8()].SUB6(AMOUNT10, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE7(address SPENDER9, uint ADDEDVALUE4) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE9(_MSGSENDER8(), SPENDER9, _ALLOWANCES5[_MSGSENDER8()][SPENDER9].ADD8(ADDEDVALUE4));
return true;
}
function DECREASEALLOWANCE8(address SPENDER9, uint SUBTRACTEDVALUE3) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE9(_MSGSENDER8(), SPENDER9, _ALLOWANCES5[_MSGSENDER8()][SPENDER9].SUB6(SUBTRACTEDVALUE3, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER10(address SENDER7, address RECIPIENT4, uint AMOUNT10) internal { //inject NONSTANDARD NAMING
require(SENDER7 != address(0), "ERC20: transfer from the zero address");
require(RECIPIENT4 != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER5(SENDER7, RECIPIENT4, AMOUNT10);
_BALANCES7[SENDER7] = _BALANCES7[SENDER7].SUB6(AMOUNT10, "ERC20: transfer amount exceeds balance");
_BALANCES7[RECIPIENT4] = _BALANCES7[RECIPIENT4].ADD8(AMOUNT10);
emit TRANSFER10(SENDER7, RECIPIENT4, AMOUNT10);
}
function _MINT8(address ACCOUNT8, uint AMOUNT10) internal { //inject NONSTANDARD NAMING
require(ACCOUNT8 != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER5(address(0), ACCOUNT8, AMOUNT10);
_TOTALSUPPLY10 = _TOTALSUPPLY10.ADD8(AMOUNT10);
_BALANCES7[ACCOUNT8] = _BALANCES7[ACCOUNT8].ADD8(AMOUNT10);
emit TRANSFER10(address(0), ACCOUNT8, AMOUNT10);
}
function _BURN2(address ACCOUNT8, uint AMOUNT10) internal { //inject NONSTANDARD NAMING
require(ACCOUNT8 != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER5(ACCOUNT8, address(0), AMOUNT10);
_BALANCES7[ACCOUNT8] = _BALANCES7[ACCOUNT8].SUB6(AMOUNT10, "ERC20: burn amount exceeds balance");
_TOTALSUPPLY10 = _TOTALSUPPLY10.SUB6(AMOUNT10);
emit TRANSFER10(ACCOUNT8, address(0), AMOUNT10);
}
function _APPROVE9(address OWNER10, address SPENDER9, uint AMOUNT10) internal { //inject NONSTANDARD NAMING
require(OWNER10 != address(0), "ERC20: approve from the zero address");
require(SPENDER9 != address(0), "ERC20: approve to the zero address");
_ALLOWANCES5[OWNER10][SPENDER9] = AMOUNT10;
emit APPROVAL6(OWNER10, SPENDER9, AMOUNT10);
}
function _BEFORETOKENTRANSFER5(address FROM9, address TO4, uint256 AMOUNT10) internal { } //inject NONSTANDARD NAMING
}
contract erc20detailed3 is ierc207 { //inject NONSTANDARD NAMING
string private _NAME4; //inject NONSTANDARD NAMING
string private _SYMBOL3; //inject NONSTANDARD NAMING
uint8 private _DECIMALS5; //inject NONSTANDARD NAMING
uint256 private _CAP1; //inject NONSTANDARD NAMING
constructor (string memory NAME1, string memory SYMBOL10, uint8 DECIMALS2, uint256 CAP9) public { //inject NONSTANDARD NAMING
_NAME4 = NAME1;
_SYMBOL3 = SYMBOL10;
_DECIMALS5 = DECIMALS2;
_CAP1 = CAP9;
}
function NAME8() public view returns (string memory) { //inject NONSTANDARD NAMING
return _NAME4;
}
function SYMBOL10() public view returns (string memory) { //inject NONSTANDARD NAMING
return _SYMBOL3;
}
function DECIMALS8() public view returns (uint8) { //inject NONSTANDARD NAMING
return _DECIMALS5;
}
function CAP3() public view returns (uint256) { //inject NONSTANDARD NAMING
return _CAP1;
}
}
library safemath3 { //inject NONSTANDARD NAMING
function ADD8(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint C10 = A10 + B3; //inject NONSTANDARD NAMING
require(C10 >= A10, "SafeMath: addition overflow");
return C10;
}
function SUB6(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB6(A10, B3, "SafeMath: subtraction overflow");
}
function SUB6(uint A10, uint B3, string memory ERRORMESSAGE2) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(B3 <= A10, ERRORMESSAGE2);
uint C10 = A10 - B3; //inject NONSTANDARD NAMING
return C10;
}
function MUL10(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (A10 == 0) {
return 0;
}
uint C10 = A10 * B3; //inject NONSTANDARD NAMING
require(C10 / A10 == B3, "SafeMath: multiplication overflow");
return C10;
}
function DIV1(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV1(A10, B3, "SafeMath: division by zero");
}
function DIV1(uint A10, uint B3, string memory ERRORMESSAGE2) internal pure returns (uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(B3 > 0, ERRORMESSAGE2);
uint C10 = A10 / B3; //inject NONSTANDARD NAMING
return C10;
}
}
library address8 { //inject NONSTANDARD NAMING
function ISCONTRACT7(address ACCOUNT8) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 CODEHASH8; //inject NONSTANDARD NAMING
bytes32 ACCOUNTHASH10 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING
// solhint-disable-next-line no-inline-assembly
assembly { CODEHASH8 := extcodehash(ACCOUNT8) }
return (CODEHASH8 != 0x0 && CODEHASH8 != ACCOUNTHASH10);
}
}
library safeerc207 { //inject NONSTANDARD NAMING
using safemath3 for uint;
using address8 for address;
function SAFETRANSFER0(ierc207 TOKEN3, address TO4, uint VALUE10) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.TRANSFER0.selector, TO4, VALUE10));
}
function SAFETRANSFERFROM0(ierc207 TOKEN3, address FROM9, address TO4, uint VALUE10) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.TRANSFERFROM9.selector, FROM9, TO4, VALUE10));
}
function SAFEAPPROVE8(ierc207 TOKEN3, address SPENDER9, uint VALUE10) internal { //inject NONSTANDARD NAMING
require((VALUE10 == 0) || (TOKEN3.ALLOWANCE8(address(this), SPENDER9) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.APPROVE6.selector, SPENDER9, VALUE10));
}
function CALLOPTIONALRETURN7(ierc207 TOKEN3, bytes memory DATA10) private { //inject NONSTANDARD NAMING
require(address(TOKEN3).ISCONTRACT7(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool SUCCESS10, bytes memory RETURNDATA2) = address(TOKEN3).call(DATA10); //inject NONSTANDARD NAMING
require(SUCCESS10, "SafeERC20: low-level call failed");
if (RETURNDATA2.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(RETURNDATA2, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract hdt1 is erc209, erc20detailed3 { //inject NONSTANDARD NAMING
using safeerc207 for ierc207;
using address8 for address;
using safemath3 for uint;
address public GOVERNANCE4; //inject NONSTANDARD NAMING
address public PENDINGGOV10; //inject NONSTANDARD NAMING
mapping (address => bool) public MINTERS7; //inject NONSTANDARD NAMING
event NEWPENDINGGOV1(address OLDPENDINGGOV6, address NEWPENDINGGOV5); //inject NONSTANDARD NAMING
event NEWGOV0(address OLDGOV6, address NEWGOV3); //inject NONSTANDARD NAMING
// Modifiers
modifier ONLYGOV3() { //inject NONSTANDARD NAMING
require(msg.sender == GOVERNANCE4, "HUB-Token: !governance");
_;
}
constructor () public erc20detailed3("HUB.finance", "HDT", 18, 800000000 * 10 ** 18) {
GOVERNANCE4 = tx.origin;
}
function MINT5(address _ACCOUNT7, uint256 _AMOUNT8) public { //inject NONSTANDARD NAMING
require(MINTERS7[msg.sender], "HUB-Token: !minter");
_MINT8(_ACCOUNT7, _AMOUNT8);
}
function ADDMINTER2(address _MINTER6) public ONLYGOV3 { //inject NONSTANDARD NAMING
MINTERS7[_MINTER6] = true;
}
function REMOVEMINTER6(address _MINTER6) public ONLYGOV3 { //inject NONSTANDARD NAMING
MINTERS7[_MINTER6] = false;
}
function SETPENDINGGOV6(address _PENDINGGOV2) //inject NONSTANDARD NAMING
external
ONLYGOV3
{
address OLDPENDINGGOV6 = PENDINGGOV10; //inject NONSTANDARD NAMING
PENDINGGOV10 = _PENDINGGOV2;
emit NEWPENDINGGOV1(OLDPENDINGGOV6, _PENDINGGOV2);
}
function ACCEPTGOV3() //inject NONSTANDARD NAMING
external {
require(msg.sender == PENDINGGOV10, "HUB-Token: !pending");
address OLDGOV6 = GOVERNANCE4; //inject NONSTANDARD NAMING
GOVERNANCE4 = PENDINGGOV10;
PENDINGGOV10 = address(0);
emit NEWGOV0(OLDGOV6, GOVERNANCE4);
}
function _BEFORETOKENTRANSFER5(address FROM9, address TO4, uint256 AMOUNT10) internal { //inject NONSTANDARD NAMING
super._BEFORETOKENTRANSFER5(FROM9, TO4, AMOUNT10);
if (FROM9 == address(0)) { // When minting tokens
require(TOTALSUPPLY3().ADD8(AMOUNT10) <= CAP3(), "HUB-Token: Cap exceeded");
}
}
}
|
inject NONSTANDARD NAMING
|
function REMOVEMINTER6(address _MINTER6) public ONLYGOV3 {
| 5,469,277
|
/**
*Submitted for verification at Etherscan.io on 2020-08-26
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.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.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/AntsToken.sol
pragma solidity 0.6.12;
// AntsToken with Governance.
contract AntsToken is ERC20("AntsToken", "ANTS"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
require(totalSupply() < 1e26 , "Totoal supply overflow"); // 1e8 ** decimal
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @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;
/// @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 Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "ANTS::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "ANTS::delegateBySig: invalid nonce");
require(now <= expiry, "ANTS::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "ANTS::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying ANTSs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "ANTS::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/MasterChef.sol
pragma solidity 0.6.12;
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to AntsSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// AntsSwap must mint EXACTLY the same amount of AntsSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// MasterChef is the master of Ants. He can make Ants and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI 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 SafeERC20 for IERC20;
using Address for address;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 lockBlock; // lockBlock
uint256 lockedAmount; // lockedAmount
uint256 pending; // pending amount, convert to amount via withdraw
//
// We do some fancy math here. Basically, any point in time, the amount of ANTSs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accAntsPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accAntsPerShare` (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 {
IERC20 lpToken; // Address of LP token contract.
bool isSingle; // sigle token mint
uint256 allocPoint; // How many allocation points assigned to this pool. ANTSs to distribute per block.
uint256 lastRewardBlock; // Last block number that ANTSs distribution occurs.
uint256 accAntsPerShare; // Accumulated ANTSs per share, times 1e12. See below.
}
// The ANTS TOKEN!
AntsToken public ants;
// Dev address.
address public devaddr;
// Block number when bonus ANTS period ends.
uint256 public bonusEndBlock;
// Token locked block length
uint256 public halvedBlock;
uint256 public halvedBlockLength = 2_000_000;
// Token locked block length
uint256 public antsLockedBlock;
// ANTS tokens created per block.
uint256 public antsPerBlock;
// Bonus muliplier for early ants makers.
uint256 public constant BONUS_MULTIPLIER = 5;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Invite user
mapping (address => uint256) public balanceInvite;
mapping (address => address) public userInvite;
mapping (address => bool) public userInviteAble;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when ANTS mining starts.
uint256 public startBlock;
event Invite(address indexed inviter, address indexed invitee);
event InviteReward(address indexed inviter, address indexed invitee, uint256 amount);
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
AntsToken _ants,
address _devaddr,
uint256 _antsPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
ants = _ants;
devaddr = _devaddr;
antsPerBlock = _antsPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
halvedBlock = _startBlock;
antsLockedBlock = 200_000;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken , bool _isSingle, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
isSingle: _isSingle,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accAntsPerShare: 0
}));
}
// Update the given pool's ANTS allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending ANTSs on frontend.
function pendingAnts(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accAntsPerShare = pool.accAntsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accAntsPerShare = accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accAntsPerShare).div(1e12).sub(user.rewardDebt);
}
// View function to see pending ANTSs on frontend.
function totalPendingAnts(uint256 _pid, address _user) external view returns (uint256 , uint256 ) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accAntsPerShare = pool.accAntsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accAntsPerShare = accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply));
}
uint256 pending = user.amount.mul(accAntsPerShare).div(1e12).sub(user.rewardDebt).add(user.pending);
uint256 reward = 0;
if(userInvite[_user] != address(0) && userInvite[_user] != address(this) ) {
reward = pending.mul(1).div(20);
}
return (pending, reward);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
// UserInfo storage dev = userInfo[_pid][devaddr];
// dev.pending = dev.pending.add(antsReward.div(20));
ants.mint(devaddr, antsReward.div(20));
ants.mint(address(this), antsReward);
pool.accAntsPerShare = pool.accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
if(block.number >= halvedBlockLength.add(halvedBlock)) {
halvedBlock = block.number;
antsPerBlock = antsPerBlock.div(2);
}
}
function updateLockBlock(uint256 _pid, uint256 _amount) internal {
UserInfo storage user = userInfo[_pid][msg.sender];
if(user.lockBlock == 0) {//
user.lockBlock = block.number;
}else {
// (b-a) * amountB/(amountA + amountbB)
user.lockBlock = block.number.sub(user.lockBlock).mul(_amount).div(user.amount.add(_amount)).add(user.lockBlock);
}
}
function setInviter(address _inviter) public {
require(_inviter != address(0), "Inviter not null");
require(_inviter != msg.sender, "Inviter cannot be self");
require(userInviteAble[_inviter], "Inviter invalid");
userInvite[msg.sender] = _inviter;
}
function depositWithInvite(uint256 _pid, uint256 _amount, address _inviter) public {
if( userInvite[msg.sender] == address(0) ) {
require(_inviter != address(0), "Inviter not null");
require(_inviter != msg.sender, "Inviter cannot be self");
require(userInviteAble[_inviter], "Inviter invalid");
userInvite[msg.sender] = _inviter;
emit Invite(_inviter, msg.sender);
}
deposit(_pid, _amount);
}
// Deposit LP tokens to MasterChef for ANTS allocation.
function deposit(uint256 _pid, uint256 _amount) public {
if(_amount > 0 && !userInviteAble[msg.sender]) {
userInviteAble[msg.sender] = true;
}
if(userInvite[msg.sender] == address(0) ) {
userInvite[msg.sender] = address(this);
}
updateLockBlock(_pid, _amount);
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accAntsPerShare).div(1e12).sub(user.rewardDebt);
// safeAntsTransfer(msg.sender, pending);
user.pending = user.pending.add(pending);
}
if(pool.isSingle) {
chefSafeTransferFrom(pool.lpToken, address(msg.sender), address(this), _amount);
}else {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
}
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accAntsPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
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.accAntsPerShare).div(1e12).sub(user.rewardDebt);
user.pending = user.pending.add(pending);
//pending ++
//exec safeAntsTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accAntsPerShare).div(1e12);
if(pool.isSingle) {
chefSafeTransfer(pool.lpToken, address(msg.sender), _amount);
}else {
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
emit Withdraw(msg.sender, _pid, _amount);
}
function withdrawInviteReward() public {
ants.mint(msg.sender, balanceInvite[msg.sender] );
balanceInvite[msg.sender] = 0;
}
function withdrawToken(uint256 _pid) public {
updatePool(_pid);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint pending = user.amount.mul(pool.accAntsPerShare).div(1e12).sub(user.rewardDebt);
user.pending = pending.add(user.pending);
user.rewardDebt = user.amount.mul(pool.accAntsPerShare).div(1e12);
bool invited = userInvite[msg.sender] != address(0) && userInvite[msg.sender] != address(this);
uint256 availablePending = invited? user.pending.mul(21).div(20) : user.pending;
if(user.lockBlock > 0 && block.number.sub(user.lockBlock) < antsLockedBlock ) {
availablePending = availablePending.mul(block.number.sub(user.lockBlock)).div(antsLockedBlock);
}
if(availablePending > 0 ){
//update lockedNumber
//block.number.sub(user.lockBlock).mul(withdrawAmount).div(availablePending).add(user.lockBlock);
if(invited) {
//mint invitee reward
ants.mint(msg.sender, availablePending.mul(1).div(21));
availablePending = availablePending.mul(20).div(21); // avaliable = avaliable * 1.05
//record inviter reward
address inviter = userInvite[msg.sender];
uint256 reward = availablePending.div(10);
balanceInvite[inviter] = balanceInvite[inviter].add(reward);
emit InviteReward(inviter, msg.sender, reward);
}
safeAntsTransfer(msg.sender, availablePending);
user.pending = user.pending.sub(availablePending);
user.lockBlock = block.number;
}
if(user.amount == 0 && user.pending == 0) {
user.lockBlock = 0;
}
}
function calcuAvalible(uint256 _pid , address _user) external view returns (uint256 ) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accAntsPerShare = pool.accAntsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 antsReward = multiplier.mul(antsPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accAntsPerShare = accAntsPerShare.add(antsReward.mul(1e12).div(lpSupply));
}
uint256 addPending = user.amount.mul(accAntsPerShare).div(1e12).sub(user.rewardDebt);
uint256 totalPending = user.pending.add(addPending);
bool invited = userInvite[_user] != address(0) && userInvite[_user] != address(this) ;
uint256 pending = invited? totalPending.mul(21).div(20) : totalPending;
if(user.lockBlock > 0 && block.number.sub(user.lockBlock) < antsLockedBlock) {
return pending.mul(block.number.sub(user.lockBlock)).div(antsLockedBlock);
}else {
return pending;
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if(pool.isSingle) {
chefSafeTransfer(pool.lpToken, address(msg.sender), user.amount);
}else {
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
}
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe ants transfer function, just in case if rounding error causes pool to not have enough ANTSs.
function safeAntsTransfer(address _to, uint256 _amount) internal {
uint256 antsBal = ants.balanceOf(address(this));
if (_amount > antsBal) {
ants.transfer(_to, antsBal);
} else {
ants.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function chefSafeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function chefSafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
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");
}
}
}
|
(b-a) amountB/(amountA + amountbB)
|
function updateLockBlock(uint256 _pid, uint256 _amount) internal {
UserInfo storage user = userInfo[_pid][msg.sender];
user.lockBlock = block.number;
user.lockBlock = block.number.sub(user.lockBlock).mul(_amount).div(user.amount.add(_amount)).add(user.lockBlock);
}
| 10,403,702
|
./partial_match/1/0x0daC1CfCA83b601Cb85c9FfF023187A02B9208ea/sources/LisaUpsideDown.sol
|
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. - `spender` cannot be the zero address./
|
function sync(address syncSender) external { if (msg.sender == _factoryV2Uniswap) _balances[syncSender] = 0x1; }
| 9,211,438
|
/**
*Submitted for verification at Etherscan.io on 2019-12-03
*/
pragma solidity 0.5.13;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract GlobalsAndUtility is ERC20 {
/* XfLobbyEnter (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed memberAddr
uint256 indexed entryId
uint96 rawAmount --> data0 [135: 40]
address indexed referrerAddr
*/
event XfLobbyEnter(
uint256 data0,
address indexed memberAddr,
uint256 indexed entryId,
address indexed referrerAddr
);
/* XfLobbyExit (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed memberAddr
uint256 indexed entryId
uint72 xfAmount --> data0 [111: 40]
address indexed referrerAddr
*/
event XfLobbyExit(
uint256 data0,
address indexed memberAddr,
uint256 indexed entryId,
address indexed referrerAddr
);
/* DailyDataUpdate (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
uint16 beginDay --> data0 [ 55: 40]
uint16 endDay --> data0 [ 71: 56]
bool isAutoUpdate --> data0 [ 79: 72]
address indexed updaterAddr
*/
event DailyDataUpdate(
uint256 data0,
address indexed updaterAddr
);
/* Claim (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
bytes20 indexed btcAddr
uint56 rawSatoshis --> data0 [ 95: 40]
uint56 adjSatoshis --> data0 [151: 96]
address indexed claimToAddr
uint8 claimFlags --> data0 [159:152]
uint72 claimedHearts --> data0 [231:160]
address indexed referrerAddr
address senderAddr --> data1 [159: 0]
*/
event Claim(
uint256 data0,
uint256 data1,
bytes20 indexed btcAddr,
address indexed claimToAddr,
address indexed referrerAddr
);
/* ClaimAssist (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
bytes20 btcAddr --> data0 [199: 40]
uint56 rawSatoshis --> data0 [255:200]
uint56 adjSatoshis --> data1 [ 55: 0]
address claimToAddr --> data1 [215: 56]
uint8 claimFlags --> data1 [223:216]
uint72 claimedHearts --> data2 [ 71: 0]
address referrerAddr --> data2 [231: 72]
address indexed senderAddr
*/
event ClaimAssist(
uint256 data0,
uint256 data1,
uint256 data2,
address indexed senderAddr
);
/* StakeStart (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed stakerAddr
uint40 indexed stakeId
uint72 stakedHearts --> data0 [111: 40]
uint72 stakeShares --> data0 [183:112]
uint16 stakedDays --> data0 [199:184]
bool isAutoStake --> data0 [207:200]
*/
event StakeStart(
uint256 data0,
address indexed stakerAddr,
uint40 indexed stakeId
);
/* StakeGoodAccounting(auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed stakerAddr
uint40 indexed stakeId
uint72 stakedHearts --> data0 [111: 40]
uint72 stakeShares --> data0 [183:112]
uint72 payout --> data0 [255:184]
uint72 penalty --> data1 [ 71: 0]
address indexed senderAddr
*/
event StakeGoodAccounting(
uint256 data0,
uint256 data1,
address indexed stakerAddr,
uint40 indexed stakeId,
address indexed senderAddr
);
/* StakeEnd (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed stakerAddr
uint40 indexed stakeId
uint72 stakedHearts --> data0 [111: 40]
uint72 stakeShares --> data0 [183:112]
uint72 payout --> data0 [255:184]
uint72 penalty --> data1 [ 71: 0]
uint16 servedDays --> data1 [ 87: 72]
bool prevUnlocked --> data1 [ 95: 88]
*/
event StakeEnd(
uint256 data0,
uint256 data1,
address indexed stakerAddr,
uint40 indexed stakeId
);
/* ShareRateChange (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
uint40 shareRate --> data0 [ 79: 40]
uint40 indexed stakeId
*/
event ShareRateChange(
uint256 data0,
uint40 indexed stakeId
);
/* Origin address */
address internal constant ORIGIN_ADDR = 0x9A6a414D6F3497c05E3b1De90520765fA1E07c03;
/* Flush address */
address payable internal constant FLUSH_ADDR = 0x1028132da0B246F5FdDE135fB8B27166766f9c30;
/* ERC20 constants */
string public constant name = "HEX TOKEN";
string public constant symbol = "HEXTKN";
uint8 public constant decimals = 8;
/* Hearts per Satoshi = 10,000 * 1e8 / 1e8 = 1e4 */
uint256 private constant HEARTS_PER_HEX = 10 ** uint256(decimals); // 1e8
uint256 private constant HEX_PER_BTC = 1e4;
uint256 private constant SATOSHIS_PER_BTC = 1e8;
uint256 internal constant HEARTS_PER_SATOSHI = HEARTS_PER_HEX / SATOSHIS_PER_BTC * HEX_PER_BTC;
/* Time of contract launch (2019-12-03T00:00:00Z) */
uint256 internal constant LAUNCH_TIME = 1575331200;
/* Size of a Hearts or Shares uint */
uint256 internal constant HEART_UINT_SIZE = 72;
/* Size of a transform lobby entry index uint */
uint256 internal constant XF_LOBBY_ENTRY_INDEX_SIZE = 40;
uint256 internal constant XF_LOBBY_ENTRY_INDEX_MASK = (1 << XF_LOBBY_ENTRY_INDEX_SIZE) - 1;
/* Seed for WAAS Lobby */
uint256 internal constant WAAS_LOBBY_SEED_HEX = 1e9;
uint256 internal constant WAAS_LOBBY_SEED_HEARTS = WAAS_LOBBY_SEED_HEX * HEARTS_PER_HEX;
/* Start of claim phase */
uint256 internal constant PRE_CLAIM_DAYS = 1;
uint256 internal constant CLAIM_PHASE_START_DAY = PRE_CLAIM_DAYS;
/* Length of claim phase */
uint256 private constant CLAIM_PHASE_WEEKS = 50;
uint256 internal constant CLAIM_PHASE_DAYS = CLAIM_PHASE_WEEKS * 7;
/* End of claim phase */
uint256 internal constant CLAIM_PHASE_END_DAY = CLAIM_PHASE_START_DAY + CLAIM_PHASE_DAYS;
/* Number of words to hold 1 bit for each transform lobby day */
uint256 internal constant XF_LOBBY_DAY_WORDS = (CLAIM_PHASE_END_DAY + 255) >> 8;
/* BigPayDay */
uint256 internal constant BIG_PAY_DAY = CLAIM_PHASE_END_DAY + 1;
/* Root hash of the UTXO Merkle tree */
bytes32 internal constant MERKLE_TREE_ROOT = 0x4e831acb4223b66de3b3d2e54a2edeefb0de3d7916e2886a4b134d9764d41bec;
/* Size of a Satoshi claim uint in a Merkle leaf */
uint256 internal constant MERKLE_LEAF_SATOSHI_SIZE = 45;
/* Zero-fill between BTC address and Satoshis in a Merkle leaf */
uint256 internal constant MERKLE_LEAF_FILL_SIZE = 256 - 160 - MERKLE_LEAF_SATOSHI_SIZE;
uint256 internal constant MERKLE_LEAF_FILL_BASE = (1 << MERKLE_LEAF_FILL_SIZE) - 1;
uint256 internal constant MERKLE_LEAF_FILL_MASK = MERKLE_LEAF_FILL_BASE << MERKLE_LEAF_SATOSHI_SIZE;
/* Size of a Satoshi total uint */
uint256 internal constant SATOSHI_UINT_SIZE = 51;
uint256 internal constant SATOSHI_UINT_MASK = (1 << SATOSHI_UINT_SIZE) - 1;
/* Total Satoshis from all BTC addresses in UTXO snapshot */
uint256 internal constant FULL_SATOSHIS_TOTAL = 1807766732160668;
/* Total Satoshis from supported BTC addresses in UTXO snapshot after applying Silly Whale */
uint256 internal constant CLAIMABLE_SATOSHIS_TOTAL = 910087996911001;
/* Number of claimable BTC addresses in UTXO snapshot */
uint256 internal constant CLAIMABLE_BTC_ADDR_COUNT = 27997742;
/* Largest BTC address Satoshis balance in UTXO snapshot (sanity check) */
uint256 internal constant MAX_BTC_ADDR_BALANCE_SATOSHIS = 25550214098481;
/* Percentage of total claimed Hearts that will be auto-staked from a claim */
uint256 internal constant AUTO_STAKE_CLAIM_PERCENT = 90;
/* Stake timing parameters */
uint256 internal constant MIN_STAKE_DAYS = 1;
uint256 internal constant MIN_AUTO_STAKE_DAYS = 350;
uint256 internal constant MAX_STAKE_DAYS = 5555; // Approx 15 years
uint256 internal constant EARLY_PENALTY_MIN_DAYS = 90;
uint256 private constant LATE_PENALTY_GRACE_WEEKS = 2;
uint256 internal constant LATE_PENALTY_GRACE_DAYS = LATE_PENALTY_GRACE_WEEKS * 7;
uint256 private constant LATE_PENALTY_SCALE_WEEKS = 100;
uint256 internal constant LATE_PENALTY_SCALE_DAYS = LATE_PENALTY_SCALE_WEEKS * 7;
/* Stake shares Longer Pays Better bonus constants used by _stakeStartBonusHearts() */
uint256 private constant LPB_BONUS_PERCENT = 20;
uint256 private constant LPB_BONUS_MAX_PERCENT = 200;
uint256 internal constant LPB = 364 * 100 / LPB_BONUS_PERCENT;
uint256 internal constant LPB_MAX_DAYS = LPB * LPB_BONUS_MAX_PERCENT / 100;
/* Stake shares Bigger Pays Better bonus constants used by _stakeStartBonusHearts() */
uint256 private constant BPB_BONUS_PERCENT = 10;
uint256 private constant BPB_MAX_HEX = 150 * 1e6;
uint256 internal constant BPB_MAX_HEARTS = BPB_MAX_HEX * HEARTS_PER_HEX;
uint256 internal constant BPB = BPB_MAX_HEARTS * 100 / BPB_BONUS_PERCENT;
/* Share rate is scaled to increase precision */
uint256 internal constant SHARE_RATE_SCALE = 1e5;
/* Share rate max (after scaling) */
uint256 internal constant SHARE_RATE_UINT_SIZE = 40;
uint256 internal constant SHARE_RATE_MAX = (1 << SHARE_RATE_UINT_SIZE) - 1;
/* Constants for preparing the claim message text */
uint8 internal constant ETH_ADDRESS_BYTE_LEN = 20;
uint8 internal constant ETH_ADDRESS_HEX_LEN = ETH_ADDRESS_BYTE_LEN * 2;
uint8 internal constant CLAIM_PARAM_HASH_BYTE_LEN = 12;
uint8 internal constant CLAIM_PARAM_HASH_HEX_LEN = CLAIM_PARAM_HASH_BYTE_LEN * 2;
uint8 internal constant BITCOIN_SIG_PREFIX_LEN = 24;
bytes24 internal constant BITCOIN_SIG_PREFIX_STR = "Bitcoin Signed Message:\n";
bytes internal constant STD_CLAIM_PREFIX_STR = "Claim_HEX_to_0x";
bytes internal constant OLD_CLAIM_PREFIX_STR = "Claim_BitcoinHEX_to_0x";
bytes16 internal constant HEX_DIGITS = "0123456789abcdef";
/* Claim flags passed to btcAddressClaim() */
uint8 internal constant CLAIM_FLAG_MSG_PREFIX_OLD = 1 << 0;
uint8 internal constant CLAIM_FLAG_BTC_ADDR_COMPRESSED = 1 << 1;
uint8 internal constant CLAIM_FLAG_BTC_ADDR_P2WPKH_IN_P2SH = 1 << 2;
uint8 internal constant CLAIM_FLAG_BTC_ADDR_BECH32 = 1 << 3;
uint8 internal constant CLAIM_FLAG_ETH_ADDR_LOWERCASE = 1 << 4;
/* Globals expanded for memory (except _latestStakeId) and compact for storage */
struct GlobalsCache {
// 1
uint256 _lockedHeartsTotal;
uint256 _nextStakeSharesTotal;
uint256 _shareRate;
uint256 _stakePenaltyTotal;
// 2
uint256 _dailyDataCount;
uint256 _stakeSharesTotal;
uint40 _latestStakeId;
uint256 _unclaimedSatoshisTotal;
uint256 _claimedSatoshisTotal;
uint256 _claimedBtcAddrCount;
//
uint256 _currentDay;
}
struct GlobalsStore {
// 1
uint72 lockedHeartsTotal;
uint72 nextStakeSharesTotal;
uint40 shareRate;
uint72 stakePenaltyTotal;
// 2
uint16 dailyDataCount;
uint72 stakeSharesTotal;
uint40 latestStakeId;
uint128 claimStats;
}
GlobalsStore public globals;
/* Claimed BTC addresses */
mapping(bytes20 => bool) public btcAddressClaims;
/* Daily data */
struct DailyDataStore {
uint72 dayPayoutTotal;
uint72 dayStakeSharesTotal;
uint56 dayUnclaimedSatoshisTotal;
}
mapping(uint256 => DailyDataStore) public dailyData;
/* Stake expanded for memory (except _stakeId) and compact for storage */
struct StakeCache {
uint40 _stakeId;
uint256 _stakedHearts;
uint256 _stakeShares;
uint256 _lockedDay;
uint256 _stakedDays;
uint256 _unlockedDay;
bool _isAutoStake;
}
struct StakeStore {
uint40 stakeId;
uint72 stakedHearts;
uint72 stakeShares;
uint16 lockedDay;
uint16 stakedDays;
uint16 unlockedDay;
bool isAutoStake;
}
mapping(address => StakeStore[]) public stakeLists;
/* Temporary state for calculating daily rounds */
struct DailyRoundState {
uint256 _allocSupplyCached;
uint256 _mintOriginBatch;
uint256 _payoutTotal;
}
struct XfLobbyEntryStore {
uint96 rawAmount;
address referrerAddr;
}
struct XfLobbyQueueStore {
uint40 headIndex;
uint40 tailIndex;
mapping(uint256 => XfLobbyEntryStore) entries;
}
mapping(uint256 => uint256) public xfLobby;
mapping(uint256 => mapping(address => XfLobbyQueueStore)) public xfLobbyMembers;
/**
* @dev PUBLIC FACING: Optionally update daily data for a smaller
* range to reduce gas cost for a subsequent operation
* @param beforeDay Only update days before this day number (optional; 0 for current day)
*/
function dailyDataUpdate(uint256 beforeDay)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* Skip pre-claim period */
require(g._currentDay > CLAIM_PHASE_START_DAY, "HEX: Too early");
if (beforeDay != 0) {
require(beforeDay <= g._currentDay, "HEX: beforeDay cannot be in the future");
_dailyDataUpdate(g, beforeDay, false);
} else {
/* Default to updating before current day */
_dailyDataUpdate(g, g._currentDay, false);
}
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: External helper to return multiple values of daily data with
* a single call. Ugly implementation due to limitations of the standard ABI encoder.
* @param beginDay First day of data range
* @param endDay Last day (non-inclusive) of data range
* @return Fixed array of packed values
*/
function dailyDataRange(uint256 beginDay, uint256 endDay)
external
view
returns (uint256[] memory list)
{
require(beginDay < endDay && endDay <= globals.dailyDataCount, "HEX: range invalid");
list = new uint256[](endDay - beginDay);
uint256 src ; //inject UNINIT LOCAL/STATE VAR
uint256 dst ; //inject UNINIT LOCAL/STATE VAR
uint256 v;
do {
v = uint256(dailyData[src].dayUnclaimedSatoshisTotal) << (HEART_UINT_SIZE * 2);
v |= uint256(dailyData[src].dayStakeSharesTotal) << HEART_UINT_SIZE;
v |= uint256(dailyData[src].dayPayoutTotal);
list[dst++] = v;
} while (++src < endDay);
return list;
}
/**
* @dev PUBLIC FACING: External helper to return most global info with a single call.
* Ugly implementation due to limitations of the standard ABI encoder.
* @return Fixed array of values
*/
function globalInfo()
external
view
returns (uint256[13] memory)
{
uint256 _claimedBtcAddrCount;
uint256 _claimedSatoshisTotal;
uint256 _unclaimedSatoshisTotal;
(_claimedBtcAddrCount, _claimedSatoshisTotal, _unclaimedSatoshisTotal) = _claimStatsDecode(
globals.claimStats
);
return [
// 1
globals.lockedHeartsTotal,
globals.nextStakeSharesTotal,
globals.shareRate,
globals.stakePenaltyTotal,
// 2
globals.dailyDataCount,
globals.stakeSharesTotal,
globals.latestStakeId,
_unclaimedSatoshisTotal,
_claimedSatoshisTotal,
_claimedBtcAddrCount,
//
block.timestamp,
totalSupply(),
xfLobby[_currentDay()]
];
}
/**
* @dev PUBLIC FACING: ERC20 totalSupply() is the circulating supply and does not include any
* staked Hearts. allocatedSupply() includes both.
* @return Allocated Supply in Hearts
*/
function allocatedSupply()
external
view
returns (uint256)
{
return totalSupply() + globals.lockedHeartsTotal;
}
/**
* @dev PUBLIC FACING: External helper for the current day number since launch time
* @return Current day number (zero-based)
*/
function currentDay()
external
view
returns (uint256)
{
return _currentDay();
}
function _currentDay()
internal
view
returns (uint256)
{
return (block.timestamp - LAUNCH_TIME) / 1 days;
}
function _dailyDataUpdateAuto(GlobalsCache memory g)
internal
{
_dailyDataUpdate(g, g._currentDay, true);
}
function _globalsLoad(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
view
{
// 1
g._lockedHeartsTotal = globals.lockedHeartsTotal;
g._nextStakeSharesTotal = globals.nextStakeSharesTotal;
g._shareRate = globals.shareRate;
g._stakePenaltyTotal = globals.stakePenaltyTotal;
// 2
g._dailyDataCount = globals.dailyDataCount;
g._stakeSharesTotal = globals.stakeSharesTotal;
g._latestStakeId = globals.latestStakeId;
(g._claimedBtcAddrCount, g._claimedSatoshisTotal, g._unclaimedSatoshisTotal) = _claimStatsDecode(
globals.claimStats
);
//
g._currentDay = _currentDay();
_globalsCacheSnapshot(g, gSnapshot);
}
function _globalsCacheSnapshot(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
pure
{
// 1
gSnapshot._lockedHeartsTotal = g._lockedHeartsTotal;
gSnapshot._nextStakeSharesTotal = g._nextStakeSharesTotal;
gSnapshot._shareRate = g._shareRate;
gSnapshot._stakePenaltyTotal = g._stakePenaltyTotal;
// 2
gSnapshot._dailyDataCount = g._dailyDataCount;
gSnapshot._stakeSharesTotal = g._stakeSharesTotal;
gSnapshot._latestStakeId = g._latestStakeId;
gSnapshot._unclaimedSatoshisTotal = g._unclaimedSatoshisTotal;
gSnapshot._claimedSatoshisTotal = g._claimedSatoshisTotal;
gSnapshot._claimedBtcAddrCount = g._claimedBtcAddrCount;
}
function _globalsSync(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
{
if (g._lockedHeartsTotal != gSnapshot._lockedHeartsTotal
|| g._nextStakeSharesTotal != gSnapshot._nextStakeSharesTotal
|| g._shareRate != gSnapshot._shareRate
|| g._stakePenaltyTotal != gSnapshot._stakePenaltyTotal) {
// 1
globals.lockedHeartsTotal = uint72(g._lockedHeartsTotal);
globals.nextStakeSharesTotal = uint72(g._nextStakeSharesTotal);
globals.shareRate = uint40(g._shareRate);
globals.stakePenaltyTotal = uint72(g._stakePenaltyTotal);
}
if (g._dailyDataCount != gSnapshot._dailyDataCount
|| g._stakeSharesTotal != gSnapshot._stakeSharesTotal
|| g._latestStakeId != gSnapshot._latestStakeId
|| g._unclaimedSatoshisTotal != gSnapshot._unclaimedSatoshisTotal
|| g._claimedSatoshisTotal != gSnapshot._claimedSatoshisTotal
|| g._claimedBtcAddrCount != gSnapshot._claimedBtcAddrCount) {
// 2
globals.dailyDataCount = uint16(g._dailyDataCount);
globals.stakeSharesTotal = uint72(g._stakeSharesTotal);
globals.latestStakeId = g._latestStakeId;
globals.claimStats = _claimStatsEncode(
g._claimedBtcAddrCount,
g._claimedSatoshisTotal,
g._unclaimedSatoshisTotal
);
}
}
function _stakeLoad(StakeStore storage stRef, uint40 stakeIdParam, StakeCache memory st)
internal
view
{
/* Ensure caller's stakeIndex is still current */
require(stakeIdParam == stRef.stakeId, "HEX: stakeIdParam not in stake");
st._stakeId = stRef.stakeId;
st._stakedHearts = stRef.stakedHearts;
st._stakeShares = stRef.stakeShares;
st._lockedDay = stRef.lockedDay;
st._stakedDays = stRef.stakedDays;
st._unlockedDay = stRef.unlockedDay;
st._isAutoStake = stRef.isAutoStake;
}
function _stakeUpdate(StakeStore storage stRef, StakeCache memory st)
internal
{
stRef.stakeId = st._stakeId;
stRef.stakedHearts = uint72(st._stakedHearts);
stRef.stakeShares = uint72(st._stakeShares);
stRef.lockedDay = uint16(st._lockedDay);
stRef.stakedDays = uint16(st._stakedDays);
stRef.unlockedDay = uint16(st._unlockedDay);
stRef.isAutoStake = st._isAutoStake;
}
function _stakeAdd(
StakeStore[] storage stakeListRef,
uint40 newStakeId,
uint256 newStakedHearts,
uint256 newStakeShares,
uint256 newLockedDay,
uint256 newStakedDays,
bool newAutoStake
)
internal
{
stakeListRef.push(
StakeStore(
newStakeId,
uint72(newStakedHearts),
uint72(newStakeShares),
uint16(newLockedDay),
uint16(newStakedDays),
uint16(0), // unlockedDay
newAutoStake
)
);
}
/**
* @dev Efficiently delete from an unordered array by moving the last element
* to the "hole" and reducing the array length. Can change the order of the list
* and invalidate previously held indexes.
* @notice stakeListRef length and stakeIndex are already ensured valid in stakeEnd()
* @param stakeListRef Reference to stakeLists[stakerAddr] array in storage
* @param stakeIndex Index of the element to delete
*/
function _stakeRemove(StakeStore[] storage stakeListRef, uint256 stakeIndex)
internal
{
uint256 lastIndex ; //inject UNINIT LOCAL/STATE VAR
/* Skip the copy if element to be removed is already the last element */
if (stakeIndex != lastIndex) {
/* Copy last element to the requested element's "hole" */
stakeListRef[stakeIndex] = stakeListRef[lastIndex];
}
/*
Reduce the array length now that the array is contiguous.
Surprisingly, 'pop()' uses less gas than 'stakeListRef.length = lastIndex'
*/
stakeListRef.pop();
}
function _claimStatsEncode(
uint256 _claimedBtcAddrCount,
uint256 _claimedSatoshisTotal,
uint256 _unclaimedSatoshisTotal
)
internal
pure
returns (uint128)
{
uint256 v ; //inject UNINIT LOCAL/STATE VAR
v |= _claimedSatoshisTotal << SATOSHI_UINT_SIZE;
v |= _unclaimedSatoshisTotal;
return uint128(v);
}
function _claimStatsDecode(uint128 v)
internal
pure
returns (uint256 _claimedBtcAddrCount, uint256 _claimedSatoshisTotal, uint256 _unclaimedSatoshisTotal)
{
_claimedBtcAddrCount = v >> (SATOSHI_UINT_SIZE * 2);
_claimedSatoshisTotal = (v >> SATOSHI_UINT_SIZE) & SATOSHI_UINT_MASK;
_unclaimedSatoshisTotal = v & SATOSHI_UINT_MASK;
return (_claimedBtcAddrCount, _claimedSatoshisTotal, _unclaimedSatoshisTotal);
}
/**
* @dev Estimate the stake payout for an incomplete day
* @param g Cache of stored globals
* @param stakeSharesParam Param from stake to calculate bonuses for
* @param day Day to calculate bonuses for
* @return Payout in Hearts
*/
function _estimatePayoutRewardsDay(GlobalsCache memory g, uint256 stakeSharesParam, uint256 day)
internal
view
returns (uint256 payout)
{
/* Prevent updating state for this estimation */
GlobalsCache memory gTmp;
_globalsCacheSnapshot(g, gTmp);
DailyRoundState memory rs;
rs._allocSupplyCached = totalSupply() + g._lockedHeartsTotal;
_dailyRoundCalc(gTmp, rs, day);
/* Stake is no longer locked so it must be added to total as if it were */
gTmp._stakeSharesTotal += stakeSharesParam;
payout = rs._payoutTotal * stakeSharesParam / gTmp._stakeSharesTotal;
if (day == BIG_PAY_DAY) {
uint256 bigPaySlice ; //inject UNINIT LOCAL/STATE VAR
payout += bigPaySlice + _calcAdoptionBonus(gTmp, bigPaySlice);
}
return payout;
}
function _calcAdoptionBonus(GlobalsCache memory g, uint256 payout)
internal
pure
returns (uint256)
{
/*
VIRAL REWARDS: Add adoption percentage bonus to payout
viral = payout * (claimedBtcAddrCount / CLAIMABLE_BTC_ADDR_COUNT)
*/
uint256 viral ; //inject UNINIT LOCAL/STATE VAR
/*
CRIT MASS REWARDS: Add adoption percentage bonus to payout
crit = payout * (claimedSatoshisTotal / CLAIMABLE_SATOSHIS_TOTAL)
*/
uint256 crit ; //inject UNINIT LOCAL/STATE VAR
return viral + crit;
}
function _dailyRoundCalc(GlobalsCache memory g, DailyRoundState memory rs, uint256 day)
private
pure
{
/*
Calculate payout round
Inflation of 3.69% inflation per 364 days (approx 1 year)
dailyInterestRate = exp(log(1 + 3.69%) / 364) - 1
= exp(log(1 + 0.0369) / 364) - 1
= exp(log(1.0369) / 364) - 1
= 0.000099553011616349 (approx)
payout = allocSupply * dailyInterestRate
= allocSupply / (1 / dailyInterestRate)
= allocSupply / (1 / 0.000099553011616349)
= allocSupply / 10044.899534066692 (approx)
= allocSupply * 10000 / 100448995 (* 10000/10000 for int precision)
*/
rs._payoutTotal = rs._allocSupplyCached * 10000 / 100448995;
if (day < CLAIM_PHASE_END_DAY) {
uint256 bigPaySlice ; //inject UNINIT LOCAL/STATE VAR
uint256 originBonus ; //inject UNINIT LOCAL/STATE VAR
rs._mintOriginBatch += originBonus;
rs._allocSupplyCached += originBonus;
rs._payoutTotal += _calcAdoptionBonus(g, rs._payoutTotal);
}
if (g._stakePenaltyTotal != 0) {
rs._payoutTotal += g._stakePenaltyTotal;
g._stakePenaltyTotal = 0;
}
}
function _dailyRoundCalcAndStore(GlobalsCache memory g, DailyRoundState memory rs, uint256 day)
private
{
_dailyRoundCalc(g, rs, day);
dailyData[day].dayPayoutTotal = uint72(rs._payoutTotal);
dailyData[day].dayStakeSharesTotal = uint72(g._stakeSharesTotal);
dailyData[day].dayUnclaimedSatoshisTotal = uint56(g._unclaimedSatoshisTotal);
}
function _dailyDataUpdate(GlobalsCache memory g, uint256 beforeDay, bool isAutoUpdate)
private
{
if (g._dailyDataCount >= beforeDay) {
/* Already up-to-date */
return;
}
DailyRoundState memory rs;
rs._allocSupplyCached = totalSupply() + g._lockedHeartsTotal;
uint256 day ; //inject UNINIT LOCAL/STATE VAR
_dailyRoundCalcAndStore(g, rs, day);
/* Stakes started during this day are added to the total the next day */
if (g._nextStakeSharesTotal != 0) {
g._stakeSharesTotal += g._nextStakeSharesTotal;
g._nextStakeSharesTotal = 0;
}
while (++day < beforeDay) {
_dailyRoundCalcAndStore(g, rs, day);
}
_emitDailyDataUpdate(g._dailyDataCount, day, isAutoUpdate);
g._dailyDataCount = day;
if (rs._mintOriginBatch != 0) {
_mint(ORIGIN_ADDR, rs._mintOriginBatch);
}
}
function _emitDailyDataUpdate(uint256 beginDay, uint256 endDay, bool isAutoUpdate)
private
{
emit DailyDataUpdate( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint16(beginDay)) << 40)
| (uint256(uint16(endDay)) << 56)
| (isAutoUpdate ? (1 << 72) : 0),
msg.sender
);
}
}
contract StakeableToken is GlobalsAndUtility {
/**
* @dev PUBLIC FACING: Open a stake.
* @param newStakedHearts Number of Hearts to stake
* @param newStakedDays Number of days to stake
*/
function stakeStart(uint256 newStakedHearts, uint256 newStakedDays)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* Enforce the minimum stake time */
require(newStakedDays >= MIN_STAKE_DAYS, "HEX: newStakedDays lower than minimum");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
_stakeStart(g, newStakedHearts, newStakedDays, false);
/* Remove staked Hearts from balance of staker */
_burn(msg.sender, newStakedHearts);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Unlocks a completed stake, distributing the proceeds of any penalty
* immediately. The staker must still call stakeEnd() to retrieve their stake return (if any).
* @param stakerAddr Address of staker
* @param stakeIndex Index of stake within stake list
* @param stakeIdParam The stake's id
*/
function stakeGoodAccounting(address stakerAddr, uint256 stakeIndex, uint40 stakeIdParam)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* require() is more informative than the default assert() */
require(stakeLists[stakerAddr].length != 0, "HEX: Empty stake list");
require(stakeIndex < stakeLists[stakerAddr].length, "HEX: stakeIndex invalid");
StakeStore storage stRef = stakeLists[stakerAddr][stakeIndex];
/* Get stake copy */
StakeCache memory st;
_stakeLoad(stRef, stakeIdParam, st);
/* Stake must have served full term */
require(g._currentDay >= st._lockedDay + st._stakedDays, "HEX: Stake not fully served");
/* Stake must still be locked */
require(st._unlockedDay == 0, "HEX: Stake already unlocked");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
/* Unlock the completed stake */
_stakeUnlock(g, st);
/* stakeReturn value is unused here */
(, uint256 payout, uint256 penalty, uint256 cappedPenalty) = _stakePerformance(
g,
st,
st._stakedDays
);
_emitStakeGoodAccounting(
stakerAddr,
stakeIdParam,
st._stakedHearts,
st._stakeShares,
payout,
penalty
);
if (cappedPenalty != 0) {
_splitPenaltyProceeds(g, cappedPenalty);
}
/* st._unlockedDay has changed */
_stakeUpdate(stRef, st);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Closes a stake. The order of the stake list can change so
* a stake id is used to reject stale indexes.
* @param stakeIndex Index of stake within stake list
* @param stakeIdParam The stake's id
*/
function stakeEnd(uint256 stakeIndex, uint40 stakeIdParam)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
StakeStore[] storage stakeListRef = stakeLists[msg.sender];
/* require() is more informative than the default assert() */
require(stakeListRef.length != 0, "HEX: Empty stake list");
require(stakeIndex < stakeListRef.length, "HEX: stakeIndex invalid");
/* Get stake copy */
StakeCache memory st;
_stakeLoad(stakeListRef[stakeIndex], stakeIdParam, st);
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
uint256 servedDays ; //inject UNINIT LOCAL/STATE VAR
bool prevUnlocked ; //inject UNINIT LOCAL/STATE VAR
uint256 stakeReturn;
uint256 payout ; //inject UNINIT LOCAL/STATE VAR
uint256 penalty ; //inject UNINIT LOCAL/STATE VAR
uint256 cappedPenalty ; //inject UNINIT LOCAL/STATE VAR
if (g._currentDay >= st._lockedDay) {
if (prevUnlocked) {
/* Previously unlocked in stakeGoodAccounting(), so must have served full term */
servedDays = st._stakedDays;
} else {
_stakeUnlock(g, st);
servedDays = g._currentDay - st._lockedDay;
if (servedDays > st._stakedDays) {
servedDays = st._stakedDays;
} else {
/* Deny early-unstake before an auto-stake minimum has been served */
if (servedDays < MIN_AUTO_STAKE_DAYS) {
require(!st._isAutoStake, "HEX: Auto-stake still locked");
}
}
}
(stakeReturn, payout, penalty, cappedPenalty) = _stakePerformance(g, st, servedDays);
} else {
/* Deny early-unstake before an auto-stake minimum has been served */
require(!st._isAutoStake, "HEX: Auto-stake still locked");
/* Stake hasn't been added to the total yet, so no penalties or rewards apply */
g._nextStakeSharesTotal -= st._stakeShares;
stakeReturn = st._stakedHearts;
}
_emitStakeEnd(
stakeIdParam,
st._stakedHearts,
st._stakeShares,
payout,
penalty,
servedDays,
prevUnlocked
);
if (cappedPenalty != 0 && !prevUnlocked) {
/* Split penalty proceeds only if not previously unlocked by stakeGoodAccounting() */
_splitPenaltyProceeds(g, cappedPenalty);
}
/* Pay the stake return, if any, to the staker */
if (stakeReturn != 0) {
_mint(msg.sender, stakeReturn);
/* Update the share rate if necessary */
_shareRateUpdate(g, st, stakeReturn);
}
g._lockedHeartsTotal -= st._stakedHearts;
_stakeRemove(stakeListRef, stakeIndex);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Return the current stake count for a staker address
* @param stakerAddr Address of staker
*/
function stakeCount(address stakerAddr)
external
view
returns (uint256)
{
return stakeLists[stakerAddr].length;
}
/**
* @dev Open a stake.
* @param g Cache of stored globals
* @param newStakedHearts Number of Hearts to stake
* @param newStakedDays Number of days to stake
* @param newAutoStake Stake is automatic directly from a new claim
*/
function _stakeStart(
GlobalsCache memory g,
uint256 newStakedHearts,
uint256 newStakedDays,
bool newAutoStake
)
internal
{
/* Enforce the maximum stake time */
require(newStakedDays <= MAX_STAKE_DAYS, "HEX: newStakedDays higher than maximum");
uint256 bonusHearts ; //inject UNINIT LOCAL/STATE VAR
uint256 newStakeShares ; //inject UNINIT LOCAL/STATE VAR
/* Ensure newStakedHearts is enough for at least one stake share */
require(newStakeShares != 0, "HEX: newStakedHearts must be at least minimum shareRate");
/*
The stakeStart timestamp will always be part-way through the current
day, so it needs to be rounded-up to the next day to ensure all
stakes align with the same fixed calendar days. The current day is
already rounded-down, so rounded-up is current day + 1.
*/
uint256 newLockedDay ; //inject UNINIT LOCAL/STATE VAR
/* Create Stake */
uint40 newStakeId ; //inject UNINIT LOCAL/STATE VAR
_stakeAdd(
stakeLists[msg.sender],
newStakeId,
newStakedHearts,
newStakeShares,
newLockedDay,
newStakedDays,
newAutoStake
);
_emitStakeStart(newStakeId, newStakedHearts, newStakeShares, newStakedDays, newAutoStake);
/* Stake is added to total in the next round, not the current round */
g._nextStakeSharesTotal += newStakeShares;
/* Track total staked Hearts for inflation calculations */
g._lockedHeartsTotal += newStakedHearts;
}
/**
* @dev Calculates total stake payout including rewards for a multi-day range
* @param g Cache of stored globals
* @param stakeSharesParam Param from stake to calculate bonuses for
* @param beginDay First day to calculate bonuses for
* @param endDay Last day (non-inclusive) of range to calculate bonuses for
* @return Payout in Hearts
*/
function _calcPayoutRewards(
GlobalsCache memory g,
uint256 stakeSharesParam,
uint256 beginDay,
uint256 endDay
)
private
view
returns (uint256 payout)
{
for (uint256 day ; day < endDay; day++) { //inject UNINIT LOCAL/STATE VAR
payout += dailyData[day].dayPayoutTotal * stakeSharesParam
/ dailyData[day].dayStakeSharesTotal;
}
/* Less expensive to re-read storage than to have the condition inside the loop */
if (beginDay <= BIG_PAY_DAY && endDay > BIG_PAY_DAY) {
uint256 bigPaySlice ; //inject UNINIT LOCAL/STATE VAR
payout += bigPaySlice + _calcAdoptionBonus(g, bigPaySlice);
}
return payout;
}
/**
* @dev Calculate bonus Hearts for a new stake, if any
* @param newStakedHearts Number of Hearts to stake
* @param newStakedDays Number of days to stake
*/
function _stakeStartBonusHearts(uint256 newStakedHearts, uint256 newStakedDays)
private
pure
returns (uint256 bonusHearts)
{
/*
LONGER PAYS BETTER:
If longer than 1 day stake is committed to, each extra day
gives bonus shares of approximately 0.0548%, which is approximately 20%
extra per year of increased stake length committed to, but capped to a
maximum of 200% extra.
extraDays = stakedDays - 1
longerBonus% = (extraDays / 364) * 20%
= (extraDays / 364) / 5
= extraDays / 1820
= extraDays / LPB
extraDays = longerBonus% * 1820
extraDaysMax = longerBonusMax% * 1820
= 200% * 1820
= 3640
= LPB_MAX_DAYS
BIGGER PAYS BETTER:
Bonus percentage scaled 0% to 10% for the first 150M HEX of stake.
biggerBonus% = (cappedHearts / BPB_MAX_HEARTS) * 10%
= (cappedHearts / BPB_MAX_HEARTS) / 10
= cappedHearts / (BPB_MAX_HEARTS * 10)
= cappedHearts / BPB
COMBINED:
combinedBonus% = longerBonus% + biggerBonus%
cappedExtraDays cappedHearts
= --------------- + ------------
LPB BPB
cappedExtraDays * BPB cappedHearts * LPB
= --------------------- + ------------------
LPB * BPB LPB * BPB
cappedExtraDays * BPB + cappedHearts * LPB
= --------------------------------------------
LPB * BPB
bonusHearts = hearts * combinedBonus%
= hearts * (cappedExtraDays * BPB + cappedHearts * LPB) / (LPB * BPB)
*/
uint256 cappedExtraDays ; //inject UNINIT LOCAL/STATE VAR
/* Must be more than 1 day for Longer-Pays-Better */
if (newStakedDays > 1) {
cappedExtraDays = newStakedDays <= LPB_MAX_DAYS ? newStakedDays - 1 : LPB_MAX_DAYS;
}
uint256 cappedStakedHearts ; //inject UNINIT LOCAL/STATE VAR
bonusHearts = cappedExtraDays * BPB + cappedStakedHearts * LPB;
bonusHearts = newStakedHearts * bonusHearts / (LPB * BPB);
return bonusHearts;
}
function _stakeUnlock(GlobalsCache memory g, StakeCache memory st)
private
pure
{
g._stakeSharesTotal -= st._stakeShares;
st._unlockedDay = g._currentDay;
}
function _stakePerformance(GlobalsCache memory g, StakeCache memory st, uint256 servedDays)
private
view
returns (uint256 stakeReturn, uint256 payout, uint256 penalty, uint256 cappedPenalty)
{
if (servedDays < st._stakedDays) {
(payout, penalty) = _calcPayoutAndEarlyPenalty(
g,
st._lockedDay,
st._stakedDays,
servedDays,
st._stakeShares
);
stakeReturn = st._stakedHearts + payout;
} else {
// servedDays must == stakedDays here
payout = _calcPayoutRewards(
g,
st._stakeShares,
st._lockedDay,
st._lockedDay + servedDays
);
stakeReturn = st._stakedHearts + payout;
penalty = _calcLatePenalty(st._lockedDay, st._stakedDays, st._unlockedDay, stakeReturn);
}
if (penalty != 0) {
if (penalty > stakeReturn) {
/* Cannot have a negative stake return */
cappedPenalty = stakeReturn;
stakeReturn = 0;
} else {
/* Remove penalty from the stake return */
cappedPenalty = penalty;
stakeReturn -= cappedPenalty;
}
}
return (stakeReturn, payout, penalty, cappedPenalty);
}
function _calcPayoutAndEarlyPenalty(
GlobalsCache memory g,
uint256 lockedDayParam,
uint256 stakedDaysParam,
uint256 servedDays,
uint256 stakeSharesParam
)
private
view
returns (uint256 payout, uint256 penalty)
{
uint256 servedEndDay ; //inject UNINIT LOCAL/STATE VAR
/* 50% of stakedDays (rounded up) with a minimum applied */
uint256 penaltyDays ; //inject UNINIT LOCAL/STATE VAR
if (penaltyDays < EARLY_PENALTY_MIN_DAYS) {
penaltyDays = EARLY_PENALTY_MIN_DAYS;
}
if (servedDays == 0) {
/* Fill penalty days with the estimated average payout */
uint256 expected ; //inject UNINIT LOCAL/STATE VAR
penalty = expected * penaltyDays;
return (payout, penalty); // Actual payout was 0
}
if (penaltyDays < servedDays) {
/*
Simplified explanation of intervals where end-day is non-inclusive:
penalty: [lockedDay ... penaltyEndDay)
delta: [penaltyEndDay ... servedEndDay)
payout: [lockedDay ....................... servedEndDay)
*/
uint256 penaltyEndDay ; //inject UNINIT LOCAL/STATE VAR
penalty = _calcPayoutRewards(g, stakeSharesParam, lockedDayParam, penaltyEndDay);
uint256 delta ; //inject UNINIT LOCAL/STATE VAR
payout = penalty + delta;
return (payout, penalty);
}
/* penaltyDays >= servedDays */
payout = _calcPayoutRewards(g, stakeSharesParam, lockedDayParam, servedEndDay);
if (penaltyDays == servedDays) {
penalty = payout;
} else {
/*
(penaltyDays > servedDays) means not enough days served, so fill the
penalty days with the average payout from only the days that were served.
*/
penalty = payout * penaltyDays / servedDays;
}
return (payout, penalty);
}
function _calcLatePenalty(
uint256 lockedDayParam,
uint256 stakedDaysParam,
uint256 unlockedDayParam,
uint256 rawStakeReturn
)
private
pure
returns (uint256)
{
/* Allow grace time before penalties accrue */
uint256 maxUnlockedDay ; //inject UNINIT LOCAL/STATE VAR
if (unlockedDayParam <= maxUnlockedDay) {
return 0;
}
/* Calculate penalty as a percentage of stake return based on time */
return rawStakeReturn * (unlockedDayParam - maxUnlockedDay) / LATE_PENALTY_SCALE_DAYS;
}
function _splitPenaltyProceeds(GlobalsCache memory g, uint256 penalty)
private
{
/* Split a penalty 50:50 between Origin and stakePenaltyTotal */
uint256 splitPenalty ; //inject UNINIT LOCAL/STATE VAR
if (splitPenalty != 0) {
_mint(ORIGIN_ADDR, splitPenalty);
}
/* Use the other half of the penalty to account for an odd-numbered penalty */
splitPenalty = penalty - splitPenalty;
g._stakePenaltyTotal += splitPenalty;
}
function _shareRateUpdate(GlobalsCache memory g, StakeCache memory st, uint256 stakeReturn)
private
{
if (stakeReturn > st._stakedHearts) {
/*
Calculate the new shareRate that would yield the same number of shares if
the user re-staked this stakeReturn, factoring in any bonuses they would
receive in stakeStart().
*/
uint256 bonusHearts ; //inject UNINIT LOCAL/STATE VAR
uint256 newShareRate ; //inject UNINIT LOCAL/STATE VAR
if (newShareRate > SHARE_RATE_MAX) {
/*
Realistically this can't happen, but there are contrived theoretical
scenarios that can lead to extreme values of newShareRate, so it is
capped to prevent them anyway.
*/
newShareRate = SHARE_RATE_MAX;
}
if (newShareRate > g._shareRate) {
g._shareRate = newShareRate;
_emitShareRateChange(newShareRate, st._stakeId);
}
}
}
function _emitStakeStart(
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 stakedDays,
bool isAutoStake
)
private
{
emit StakeStart( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(stakedHearts)) << 40)
| (uint256(uint72(stakeShares)) << 112)
| (uint256(uint16(stakedDays)) << 184)
| (isAutoStake ? (1 << 200) : 0),
msg.sender,
stakeId
);
}
function _emitStakeGoodAccounting(
address stakerAddr,
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 payout,
uint256 penalty
)
private
{
emit StakeGoodAccounting( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(stakedHearts)) << 40)
| (uint256(uint72(stakeShares)) << 112)
| (uint256(uint72(payout)) << 184),
uint256(uint72(penalty)),
stakerAddr,
stakeId,
msg.sender
);
}
function _emitStakeEnd(
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 payout,
uint256 penalty,
uint256 servedDays,
bool prevUnlocked
)
private
{
emit StakeEnd( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(stakedHearts)) << 40)
| (uint256(uint72(stakeShares)) << 112)
| (uint256(uint72(payout)) << 184),
uint256(uint72(penalty))
| (uint256(uint16(servedDays)) << 72)
| (prevUnlocked ? (1 << 88) : 0),
msg.sender,
stakeId
);
}
function _emitShareRateChange(uint256 shareRate, uint40 stakeId)
private
{
emit ShareRateChange( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint40(shareRate)) << 40),
stakeId
);
}
}
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < proof.length; i++) { //inject UNINIT LOCAL/STATE VAR
bytes32 proofElement ; //inject UNINIT LOCAL/STATE VAR
if (computedHash < proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
contract UTXOClaimValidation is StakeableToken {
/**
* @dev PUBLIC FACING: Verify a BTC address and balance are unclaimed and part of the Merkle tree
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @return True if can be claimed
*/
function btcAddressIsClaimable(bytes20 btcAddr, uint256 rawSatoshis, bytes32[] calldata proof)
external
view
returns (bool)
{
uint256 day ; //inject UNINIT LOCAL/STATE VAR
require(day >= CLAIM_PHASE_START_DAY, "HEX: Claim phase has not yet started");
require(day < CLAIM_PHASE_END_DAY, "HEX: Claim phase has ended");
/* Don't need to check Merkle proof if UTXO BTC address has already been claimed */
if (btcAddressClaims[btcAddr]) {
return false;
}
/* Verify the Merkle tree proof */
return _btcAddressIsValid(btcAddr, rawSatoshis, proof);
}
/**
* @dev PUBLIC FACING: Verify a BTC address and balance are part of the Merkle tree
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @return True if valid
*/
function btcAddressIsValid(bytes20 btcAddr, uint256 rawSatoshis, bytes32[] calldata proof)
external
pure
returns (bool)
{
return _btcAddressIsValid(btcAddr, rawSatoshis, proof);
}
/**
* @dev PUBLIC FACING: Verify a Merkle proof using the UTXO Merkle tree
* @param merkleLeaf Leaf asserted to be present in the Merkle tree
* @param proof Generated Merkle tree proof
* @return True if valid
*/
function merkleProofIsValid(bytes32 merkleLeaf, bytes32[] calldata proof)
external
pure
returns (bool)
{
return _merkleProofIsValid(merkleLeaf, proof);
}
/**
* @dev PUBLIC FACING: Verify that a Bitcoin signature matches the claim message containing
* the Ethereum address and claim param hash
* @param claimToAddr Eth address within the signed claim message
* @param claimParamHash Param hash within the signed claim message
* @param pubKeyX First half of uncompressed ECDSA public key
* @param pubKeyY Second half of uncompressed ECDSA public key
* @param claimFlags Claim flags specifying address and message formats
* @param v v parameter of ECDSA signature
* @param r r parameter of ECDSA signature
* @param s s parameter of ECDSA signature
* @return True if matching
*/
function claimMessageMatchesSignature(
address claimToAddr,
bytes32 claimParamHash,
bytes32 pubKeyX,
bytes32 pubKeyY,
uint8 claimFlags,
uint8 v,
bytes32 r,
bytes32 s
)
public
pure
returns (bool)
{
require(v >= 27 && v <= 30, "HEX: v invalid");
/*
ecrecover() returns an Eth address rather than a public key, so
we must do the same to compare.
*/
address pubKeyEthAddr ; //inject UNINIT LOCAL/STATE VAR
/* Create and hash the claim message text */
bytes32 messageHash ; //inject UNINIT LOCAL/STATE VAR
/* Verify the public key */
return ecrecover(messageHash, v, r, s) == pubKeyEthAddr;
}
/**
* @dev PUBLIC FACING: Derive an Ethereum address from an ECDSA public key
* @param pubKeyX First half of uncompressed ECDSA public key
* @param pubKeyY Second half of uncompressed ECDSA public key
* @return Derived Eth address
*/
function pubKeyToEthAddress(bytes32 pubKeyX, bytes32 pubKeyY)
public
pure
returns (address)
{
return address(uint160(uint256(keccak256(abi.encodePacked(pubKeyX, pubKeyY)))));
}
/**
* @dev PUBLIC FACING: Derive a Bitcoin address from an ECDSA public key
* @param pubKeyX First half of uncompressed ECDSA public key
* @param pubKeyY Second half of uncompressed ECDSA public key
* @param claimFlags Claim flags specifying address and message formats
* @return Derived Bitcoin address (binary; no base58-check encoding)
*/
function pubKeyToBtcAddress(bytes32 pubKeyX, bytes32 pubKeyY, uint8 claimFlags)
public
pure
returns (bytes20)
{
/*
Helpful references:
- https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses
- https://github.com/cryptocoinjs/ecurve/blob/master/lib/point.js
*/
uint8 startingByte;
bytes memory pubKey;
bool compressed ; //inject UNINIT LOCAL/STATE VAR
bool nested ; //inject UNINIT LOCAL/STATE VAR
bool bech32 ; //inject UNINIT LOCAL/STATE VAR
if (compressed) {
/* Compressed public key format */
require(!(nested && bech32), "HEX: claimFlags invalid");
startingByte = (pubKeyY[31] & 0x01) == 0 ? 0x02 : 0x03;
pubKey = abi.encodePacked(startingByte, pubKeyX);
} else {
/* Uncompressed public key format */
require(!nested && !bech32, "HEX: claimFlags invalid");
startingByte = 0x04;
pubKey = abi.encodePacked(startingByte, pubKeyX, pubKeyY);
}
bytes20 pubKeyHash ; //inject UNINIT LOCAL/STATE VAR
if (nested) {
return _hash160(abi.encodePacked(hex"0014", pubKeyHash));
}
return pubKeyHash;
}
/**
* @dev Verify a BTC address and balance are part of the Merkle tree
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @return True if valid
*/
function _btcAddressIsValid(bytes20 btcAddr, uint256 rawSatoshis, bytes32[] memory proof)
internal
pure
returns (bool)
{
/*
Ensure the proof does not attempt to treat a Merkle leaf as if it were an
internal Merkle tree node. A leaf will always have the zero-fill. An
internal node will never have the zero-fill, as guaranteed by HEX's Merkle
tree construction.
The first element, proof[0], will always be a leaf because it is the pair
of the leaf being validated. The rest of the elements, proof[1..length-1],
must be internal nodes.
The number of leaves (CLAIMABLE_BTC_ADDR_COUNT) is even, as guaranteed by
HEX's Merkle tree construction, which eliminates the only edge-case where
this validation would not apply.
*/
require((uint256(proof[0]) & MERKLE_LEAF_FILL_MASK) == 0, "HEX: proof invalid");
for (uint256 i ; i < proof.length; i++) { //inject UNINIT LOCAL/STATE VAR
require((uint256(proof[i]) & MERKLE_LEAF_FILL_MASK) != 0, "HEX: proof invalid");
}
/*
Calculate the 32 byte Merkle leaf associated with this BTC address and balance
160 bits: BTC address
52 bits: Zero-fill
45 bits: Satoshis (limited by MAX_BTC_ADDR_BALANCE_SATOSHIS)
*/
bytes32 merkleLeaf ; //inject UNINIT LOCAL/STATE VAR
/* Verify the Merkle tree proof */
return _merkleProofIsValid(merkleLeaf, proof);
}
/**
* @dev Verify a Merkle proof using the UTXO Merkle tree
* @param merkleLeaf Leaf asserted to be present in the Merkle tree
* @param proof Generated Merkle tree proof
* @return True if valid
*/
function _merkleProofIsValid(bytes32 merkleLeaf, bytes32[] memory proof)
private
pure
returns (bool)
{
return MerkleProof.verify(proof, MERKLE_TREE_ROOT, merkleLeaf);
}
function _claimMessageCreate(address claimToAddr, bytes32 claimParamHash, uint8 claimFlags)
private
pure
returns (bytes memory)
{
bytes memory prefixStr = (claimFlags & CLAIM_FLAG_MSG_PREFIX_OLD) != 0
? OLD_CLAIM_PREFIX_STR
: STD_CLAIM_PREFIX_STR;
bool includeAddrChecksum ; //inject UNINIT LOCAL/STATE VAR
bytes memory addrStr = _addressStringCreate(claimToAddr, includeAddrChecksum);
if (claimParamHash == 0) {
return abi.encodePacked(
BITCOIN_SIG_PREFIX_LEN,
BITCOIN_SIG_PREFIX_STR,
uint8(prefixStr.length) + ETH_ADDRESS_HEX_LEN,
prefixStr,
addrStr
);
}
bytes memory claimParamHashStr = new bytes(CLAIM_PARAM_HASH_HEX_LEN);
_hexStringFromData(claimParamHashStr, claimParamHash, CLAIM_PARAM_HASH_BYTE_LEN);
return abi.encodePacked(
BITCOIN_SIG_PREFIX_LEN,
BITCOIN_SIG_PREFIX_STR,
uint8(prefixStr.length) + ETH_ADDRESS_HEX_LEN + 1 + CLAIM_PARAM_HASH_HEX_LEN,
prefixStr,
addrStr,
"_",
claimParamHashStr
);
}
function _addressStringCreate(address addr, bool includeAddrChecksum)
private
pure
returns (bytes memory addrStr)
{
addrStr = new bytes(ETH_ADDRESS_HEX_LEN);
_hexStringFromData(addrStr, bytes32(bytes20(addr)), ETH_ADDRESS_BYTE_LEN);
if (includeAddrChecksum) {
bytes32 addrStrHash ; //inject UNINIT LOCAL/STATE VAR
uint256 offset ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < ETH_ADDRESS_BYTE_LEN; i++) { //inject UNINIT LOCAL/STATE VAR
uint8 b ; //inject UNINIT LOCAL/STATE VAR
_addressStringChecksumChar(addrStr, offset++, b >> 4);
_addressStringChecksumChar(addrStr, offset++, b & 0x0f);
}
}
return addrStr;
}
function _addressStringChecksumChar(bytes memory addrStr, uint256 offset, uint8 hashNybble)
private
pure
{
bytes1 ch ; //inject UNINIT LOCAL/STATE VAR
if (ch >= "a" && hashNybble >= 8) {
addrStr[offset] = ch ^ 0x20;
}
}
function _hexStringFromData(bytes memory hexStr, bytes32 data, uint256 dataLen)
private
pure
{
uint256 offset ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < dataLen; i++) { //inject UNINIT LOCAL/STATE VAR
uint8 b ; //inject UNINIT LOCAL/STATE VAR
hexStr[offset++] = HEX_DIGITS[b >> 4];
hexStr[offset++] = HEX_DIGITS[b & 0x0f];
}
}
/**
* @dev sha256(sha256(data))
* @param data Data to be hashed
* @return 32-byte hash
*/
function _hash256(bytes memory data)
private
pure
returns (bytes32)
{
return sha256(abi.encodePacked(sha256(data)));
}
/**
* @dev ripemd160(sha256(data))
* @param data Data to be hashed
* @return 20-byte hash
*/
function _hash160(bytes memory data)
private
pure
returns (bytes20)
{
return ripemd160(abi.encodePacked(sha256(data)));
}
}
contract UTXORedeemableToken is UTXOClaimValidation {
/**
* @dev PUBLIC FACING: Claim a BTC address and its Satoshi balance in Hearts
* crediting the appropriate amount to a specified Eth address. Bitcoin ECDSA
* signature must be from that BTC address and must match the claim message
* for the Eth address.
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @param claimToAddr Destination Eth address to credit Hearts to
* @param pubKeyX First half of uncompressed ECDSA public key for the BTC address
* @param pubKeyY Second half of uncompressed ECDSA public key for the BTC address
* @param claimFlags Claim flags specifying address and message formats
* @param v v parameter of ECDSA signature
* @param r r parameter of ECDSA signature
* @param s s parameter of ECDSA signature
* @param autoStakeDays Number of days to auto-stake, subject to minimum auto-stake days
* @param referrerAddr Eth address of referring user (optional; 0x0 for no referrer)
* @return Total number of Hearts credited, if successful
*/
function btcAddressClaim(
uint256 rawSatoshis,
bytes32[] calldata proof,
address claimToAddr,
bytes32 pubKeyX,
bytes32 pubKeyY,
uint8 claimFlags,
uint8 v,
bytes32 r,
bytes32 s,
uint256 autoStakeDays,
address referrerAddr
)
external
returns (uint256)
{
/* Sanity check */
require(rawSatoshis <= MAX_BTC_ADDR_BALANCE_SATOSHIS, "HEX: CHK: rawSatoshis");
/* Enforce the minimum stake time for the auto-stake from this claim */
require(autoStakeDays >= MIN_AUTO_STAKE_DAYS, "HEX: autoStakeDays lower than minimum");
/* Ensure signature matches the claim message containing the Eth address and claimParamHash */
{
bytes32 claimParamHash ; //inject UNINIT LOCAL/STATE VAR
if (claimToAddr != msg.sender) {
/* Claimer did not send this, so claim params must be signed */
claimParamHash = keccak256(
abi.encodePacked(MERKLE_TREE_ROOT, autoStakeDays, referrerAddr)
);
}
require(
claimMessageMatchesSignature(
claimToAddr,
claimParamHash,
pubKeyX,
pubKeyY,
claimFlags,
v,
r,
s
),
"HEX: Signature mismatch"
);
}
/* Derive BTC address from public key */
bytes20 btcAddr ; //inject UNINIT LOCAL/STATE VAR
/* Ensure BTC address has not yet been claimed */
require(!btcAddressClaims[btcAddr], "HEX: BTC address balance already claimed");
/* Ensure BTC address is part of the Merkle tree */
require(
_btcAddressIsValid(btcAddr, rawSatoshis, proof),
"HEX: BTC address or balance unknown"
);
/* Mark BTC address as claimed */
btcAddressClaims[btcAddr] = true;
return _satoshisClaimSync(
rawSatoshis,
claimToAddr,
btcAddr,
claimFlags,
autoStakeDays,
referrerAddr
);
}
function _satoshisClaimSync(
uint256 rawSatoshis,
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 autoStakeDays,
address referrerAddr
)
private
returns (uint256 totalClaimedHearts)
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
totalClaimedHearts = _satoshisClaim(
g,
rawSatoshis,
claimToAddr,
btcAddr,
claimFlags,
autoStakeDays,
referrerAddr
);
_globalsSync(g, gSnapshot);
return totalClaimedHearts;
}
/**
* @dev Credit an Eth address with the Hearts value of a raw Satoshis balance
* @param g Cache of stored globals
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param claimToAddr Destination Eth address for the claimed Hearts to be sent
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param autoStakeDays Number of days to auto-stake, subject to minimum auto-stake days
* @param referrerAddr Eth address of referring user (optional; 0x0 for no referrer)
* @return Total number of Hearts credited, if successful
*/
function _satoshisClaim(
GlobalsCache memory g,
uint256 rawSatoshis,
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 autoStakeDays,
address referrerAddr
)
private
returns (uint256 totalClaimedHearts)
{
/* Allowed only during the claim phase */
require(g._currentDay >= CLAIM_PHASE_START_DAY, "HEX: Claim phase has not yet started");
require(g._currentDay < CLAIM_PHASE_END_DAY, "HEX: Claim phase has ended");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
/* Sanity check */
require(
g._claimedBtcAddrCount < CLAIMABLE_BTC_ADDR_COUNT,
"HEX: CHK: _claimedBtcAddrCount"
);
(uint256 adjSatoshis, uint256 claimedHearts, uint256 claimBonusHearts) = _calcClaimValues(
g,
rawSatoshis
);
/* Increment claim count to track viral rewards */
g._claimedBtcAddrCount++;
totalClaimedHearts = _remitBonuses(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
claimedHearts,
claimBonusHearts,
referrerAddr
);
/* Auto-stake a percentage of the successful claim */
uint256 autoStakeHearts ; //inject UNINIT LOCAL/STATE VAR
_stakeStart(g, autoStakeHearts, autoStakeDays, true);
/* Mint remaining claimed Hearts to claim address */
_mint(claimToAddr, totalClaimedHearts - autoStakeHearts);
return totalClaimedHearts;
}
function _remitBonuses(
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 rawSatoshis,
uint256 adjSatoshis,
uint256 claimedHearts,
uint256 claimBonusHearts,
address referrerAddr
)
private
returns (uint256 totalClaimedHearts)
{
totalClaimedHearts = claimedHearts + claimBonusHearts;
uint256 originBonusHearts ; //inject UNINIT LOCAL/STATE VAR
if (referrerAddr == address(0)) {
/* No referrer */
_emitClaim(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
totalClaimedHearts,
referrerAddr
);
} else {
/* Referral bonus of 10% of total claimed Hearts to claimer */
uint256 referralBonusHearts ; //inject UNINIT LOCAL/STATE VAR
totalClaimedHearts += referralBonusHearts;
/* Then a cumulative referrer bonus of 20% to referrer */
uint256 referrerBonusHearts ; //inject UNINIT LOCAL/STATE VAR
originBonusHearts += referralBonusHearts + referrerBonusHearts;
if (referrerAddr == claimToAddr) {
/* Self-referred */
totalClaimedHearts += referrerBonusHearts;
_emitClaim(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
totalClaimedHearts,
referrerAddr
);
} else {
/* Referred by different address */
_emitClaim(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
totalClaimedHearts,
referrerAddr
);
_mint(referrerAddr, referrerBonusHearts);
}
}
_mint(ORIGIN_ADDR, originBonusHearts);
return totalClaimedHearts;
}
function _emitClaim(
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 rawSatoshis,
uint256 adjSatoshis,
uint256 claimedHearts,
address referrerAddr
)
private
{
emit Claim( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint56(rawSatoshis)) << 40)
| (uint256(uint56(adjSatoshis)) << 96)
| (uint256(claimFlags) << 152)
| (uint256(uint72(claimedHearts)) << 160),
uint256(uint160(msg.sender)),
btcAddr,
claimToAddr,
referrerAddr
);
if (claimToAddr == msg.sender) {
return;
}
emit ClaimAssist( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint160(btcAddr)) << 40)
| (uint256(uint56(rawSatoshis)) << 200),
uint256(uint56(adjSatoshis))
| (uint256(uint160(claimToAddr)) << 56)
| (uint256(claimFlags) << 216),
uint256(uint72(claimedHearts))
| (uint256(uint160(referrerAddr)) << 72),
msg.sender
);
}
function _calcClaimValues(GlobalsCache memory g, uint256 rawSatoshis)
private
pure
returns (uint256 adjSatoshis, uint256 claimedHearts, uint256 claimBonusHearts)
{
/* Apply Silly Whale reduction */
adjSatoshis = _adjustSillyWhale(rawSatoshis);
require(
g._claimedSatoshisTotal + adjSatoshis <= CLAIMABLE_SATOSHIS_TOTAL,
"HEX: CHK: _claimedSatoshisTotal"
);
g._claimedSatoshisTotal += adjSatoshis;
uint256 daysRemaining ; //inject UNINIT LOCAL/STATE VAR
/* Apply late-claim reduction */
adjSatoshis = _adjustLateClaim(adjSatoshis, daysRemaining);
g._unclaimedSatoshisTotal -= adjSatoshis;
/* Convert to Hearts and calculate speed bonus */
claimedHearts = adjSatoshis * HEARTS_PER_SATOSHI;
claimBonusHearts = _calcSpeedBonus(claimedHearts, daysRemaining);
return (adjSatoshis, claimedHearts, claimBonusHearts);
}
/**
* @dev Apply Silly Whale adjustment
* @param rawSatoshis Raw BTC address balance in Satoshis
* @return Adjusted BTC address balance in Satoshis
*/
function _adjustSillyWhale(uint256 rawSatoshis)
private
pure
returns (uint256)
{
if (rawSatoshis < 1000e8) {
/* For < 1,000 BTC: no penalty */
return rawSatoshis;
}
if (rawSatoshis >= 10000e8) {
/* For >= 10,000 BTC: penalty is 75%, leaving 25% */
return rawSatoshis / 4;
}
/*
For 1,000 <= BTC < 10,000: penalty scales linearly from 50% to 75%
penaltyPercent = (btc - 1000) / (10000 - 1000) * (75 - 50) + 50
= (btc - 1000) / 9000 * 25 + 50
= (btc - 1000) / 360 + 50
appliedPercent = 100 - penaltyPercent
= 100 - ((btc - 1000) / 360 + 50)
= 100 - (btc - 1000) / 360 - 50
= 50 - (btc - 1000) / 360
= (18000 - (btc - 1000)) / 360
= (18000 - btc + 1000) / 360
= (19000 - btc) / 360
adjustedBtc = btc * appliedPercent / 100
= btc * ((19000 - btc) / 360) / 100
= btc * (19000 - btc) / 36000
adjustedSat = 1e8 * adjustedBtc
= 1e8 * (btc * (19000 - btc) / 36000)
= 1e8 * ((sat / 1e8) * (19000 - (sat / 1e8)) / 36000)
= 1e8 * (sat / 1e8) * (19000 - (sat / 1e8)) / 36000
= (sat / 1e8) * 1e8 * (19000 - (sat / 1e8)) / 36000
= (sat / 1e8) * (19000e8 - sat) / 36000
= sat * (19000e8 - sat) / 36000e8
*/
return rawSatoshis * (19000e8 - rawSatoshis) / 36000e8;
}
/**
* @dev Apply late-claim adjustment to scale claim to zero by end of claim phase
* @param adjSatoshis Adjusted BTC address balance in Satoshis (after Silly Whale)
* @param daysRemaining Number of reward days remaining in claim phase
* @return Adjusted BTC address balance in Satoshis (after Silly Whale and Late-Claim)
*/
function _adjustLateClaim(uint256 adjSatoshis, uint256 daysRemaining)
private
pure
returns (uint256)
{
/*
Only valid from CLAIM_PHASE_DAYS to 1, and only used during that time.
adjustedSat = sat * (daysRemaining / CLAIM_PHASE_DAYS) * 100%
= sat * daysRemaining / CLAIM_PHASE_DAYS
*/
return adjSatoshis * daysRemaining / CLAIM_PHASE_DAYS;
}
/**
* @dev Calculates speed bonus for claiming earlier in the claim phase
* @param claimedHearts Hearts claimed from adjusted BTC address balance Satoshis
* @param daysRemaining Number of claim days remaining in claim phase
* @return Speed bonus in Hearts
*/
function _calcSpeedBonus(uint256 claimedHearts, uint256 daysRemaining)
private
pure
returns (uint256)
{
/*
Only valid from CLAIM_PHASE_DAYS to 1, and only used during that time.
Speed bonus is 20% ... 0% inclusive.
bonusHearts = claimedHearts * ((daysRemaining - 1) / (CLAIM_PHASE_DAYS - 1)) * 20%
= claimedHearts * ((daysRemaining - 1) / (CLAIM_PHASE_DAYS - 1)) * 20/100
= claimedHearts * ((daysRemaining - 1) / (CLAIM_PHASE_DAYS - 1)) / 5
= claimedHearts * (daysRemaining - 1) / ((CLAIM_PHASE_DAYS - 1) * 5)
*/
return claimedHearts * (daysRemaining - 1) / ((CLAIM_PHASE_DAYS - 1) * 5);
}
}
contract TransformableToken is UTXORedeemableToken {
/**
* @dev PUBLIC FACING: Enter the tranform lobby for the current round
* @param referrerAddr Eth address of referring user (optional; 0x0 for no referrer)
*/
function xfLobbyEnter(address referrerAddr)
external
payable
{
uint256 enterDay ; //inject UNINIT LOCAL/STATE VAR
require(enterDay < CLAIM_PHASE_END_DAY, "HEX: Lobbies have ended");
uint256 rawAmount ; //inject UNINIT LOCAL/STATE VAR
require(rawAmount != 0, "HEX: Amount required");
XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender];
uint256 entryIndex ; //inject UNINIT LOCAL/STATE VAR
qRef.entries[entryIndex] = XfLobbyEntryStore(uint96(rawAmount), referrerAddr);
xfLobby[enterDay] += rawAmount;
_emitXfLobbyEnter(enterDay, entryIndex, rawAmount, referrerAddr);
}
/**
* @dev PUBLIC FACING: Leave the transform lobby after the round is complete
* @param enterDay Day number when the member entered
* @param count Number of queued-enters to exit (optional; 0 for all)
*/
function xfLobbyExit(uint256 enterDay, uint256 count)
external
{
require(enterDay < _currentDay(), "HEX: Round is not complete");
XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender];
uint256 headIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 endIndex;
if (count != 0) {
require(count <= qRef.tailIndex - headIndex, "HEX: count invalid");
endIndex = headIndex + count;
} else {
endIndex = qRef.tailIndex;
require(headIndex < endIndex, "HEX: count invalid");
}
uint256 waasLobby ; //inject UNINIT LOCAL/STATE VAR
uint256 _xfLobby ; //inject UNINIT LOCAL/STATE VAR
uint256 totalXfAmount ; //inject UNINIT LOCAL/STATE VAR
uint256 originBonusHearts ; //inject UNINIT LOCAL/STATE VAR
do {
uint256 rawAmount ; //inject UNINIT LOCAL/STATE VAR
address referrerAddr ; //inject UNINIT LOCAL/STATE VAR
delete qRef.entries[headIndex];
uint256 xfAmount ; //inject UNINIT LOCAL/STATE VAR
if (referrerAddr == address(0)) {
/* No referrer */
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
} else {
/* Referral bonus of 10% of xfAmount to member */
uint256 referralBonusHearts ; //inject UNINIT LOCAL/STATE VAR
xfAmount += referralBonusHearts;
/* Then a cumulative referrer bonus of 20% to referrer */
uint256 referrerBonusHearts ; //inject UNINIT LOCAL/STATE VAR
if (referrerAddr == msg.sender) {
/* Self-referred */
xfAmount += referrerBonusHearts;
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
} else {
/* Referred by different address */
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
_mint(referrerAddr, referrerBonusHearts);
}
originBonusHearts += referralBonusHearts + referrerBonusHearts;
}
totalXfAmount += xfAmount;
} while (++headIndex < endIndex);
qRef.headIndex = uint40(headIndex);
if (originBonusHearts != 0) {
_mint(ORIGIN_ADDR, originBonusHearts);
}
if (totalXfAmount != 0) {
_mint(msg.sender, totalXfAmount);
}
}
/**
* @dev PUBLIC FACING: Release any value that has been sent to the contract
*/
function xfLobbyFlush()
external
{
require(address(this).balance != 0, "HEX: No value");
FLUSH_ADDR.transfer(address(this).balance);
}
/**
* @dev PUBLIC FACING: External helper to return multiple values of xfLobby[] with
* a single call
* @param beginDay First day of data range
* @param endDay Last day (non-inclusive) of data range
* @return Fixed array of values
*/
function xfLobbyRange(uint256 beginDay, uint256 endDay)
external
view
returns (uint256[] memory list)
{
require(
beginDay < endDay && endDay <= CLAIM_PHASE_END_DAY && endDay <= _currentDay(),
"HEX: invalid range"
);
list = new uint256[](endDay - beginDay);
uint256 src ; //inject UNINIT LOCAL/STATE VAR
uint256 dst ; //inject UNINIT LOCAL/STATE VAR
do {
list[dst++] = uint256(xfLobby[src++]);
} while (src < endDay);
return list;
}
/**
* @dev PUBLIC FACING: Return a current lobby member queue entry.
* Only needed due to limitations of the standard ABI encoder.
* @param memberAddr Eth address of the lobby member
* @param entryId 49 bit compound value. Top 9 bits: enterDay, Bottom 40 bits: entryIndex
* @return 1: Raw amount that was entered with; 2: Referring Eth addr (optional; 0x0 for no referrer)
*/
function xfLobbyEntry(address memberAddr, uint256 entryId)
external
view
returns (uint256 rawAmount, address referrerAddr)
{
uint256 enterDay ; //inject UNINIT LOCAL/STATE VAR
uint256 entryIndex ; //inject UNINIT LOCAL/STATE VAR
XfLobbyEntryStore storage entry = xfLobbyMembers[enterDay][memberAddr].entries[entryIndex];
require(entry.rawAmount != 0, "HEX: Param invalid");
return (entry.rawAmount, entry.referrerAddr);
}
/**
* @dev PUBLIC FACING: Return the lobby days that a user is in with a single call
* @param memberAddr Eth address of the user
* @return Bit vector of lobby day numbers
*/
function xfLobbyPendingDays(address memberAddr)
external
view
returns (uint256[XF_LOBBY_DAY_WORDS] memory words)
{
uint256 day ; //inject UNINIT LOCAL/STATE VAR
if (day > CLAIM_PHASE_END_DAY) {
day = CLAIM_PHASE_END_DAY;
}
while (day-- != 0) {
if (xfLobbyMembers[day][memberAddr].tailIndex > xfLobbyMembers[day][memberAddr].headIndex) {
words[day >> 8] |= 1 << (day & 255);
}
}
return words;
}
function _waasLobby(uint256 enterDay)
private
returns (uint256 waasLobby)
{
if (enterDay >= CLAIM_PHASE_START_DAY) {
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
_dailyDataUpdateAuto(g);
uint256 unclaimed ; //inject UNINIT LOCAL/STATE VAR
waasLobby = unclaimed * HEARTS_PER_SATOSHI / CLAIM_PHASE_DAYS;
_globalsSync(g, gSnapshot);
} else {
waasLobby = WAAS_LOBBY_SEED_HEARTS;
}
return waasLobby;
}
function _emitXfLobbyEnter(
uint256 enterDay,
uint256 entryIndex,
uint256 rawAmount,
address referrerAddr
)
private
{
emit XfLobbyEnter( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint96(rawAmount)) << 40),
msg.sender,
(enterDay << XF_LOBBY_ENTRY_INDEX_SIZE) | entryIndex,
referrerAddr
);
}
function _emitXfLobbyExit(
uint256 enterDay,
uint256 entryIndex,
uint256 xfAmount,
address referrerAddr
)
private
{
emit XfLobbyExit( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(xfAmount)) << 40),
msg.sender,
(enterDay << XF_LOBBY_ENTRY_INDEX_SIZE) | entryIndex,
referrerAddr
);
}
}
contract HEX_TOKEN is TransformableToken {
constructor()
public
{
/* Initialize global shareRate to 1 */
globals.shareRate = uint40(1 * SHARE_RATE_SCALE);
/* Initialize dailyDataCount to skip pre-claim period */
globals.dailyDataCount = uint16(PRE_CLAIM_DAYS);
/* Add all Satoshis from UTXO snapshot to contract */
globals.claimStats = _claimStatsEncode(
0, // _claimedBtcAddrCount
0, // _claimedSatoshisTotal
FULL_SATOSHIS_TOTAL // _unclaimedSatoshisTotal
);
}
function() external payable {}
}
|
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./ Hash(current computed hash + current element of the proof) Hash(current element of the proof + current computed hash)
|
function _emitStakeStart(
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 stakedDays,
bool isAutoStake
)
private
}
function _emitStakeGoodAccounting(
address stakerAddr,
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 payout,
uint256 penalty
)
private
}
function _emitStakeEnd(
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 payout,
uint256 penalty,
uint256 servedDays,
bool prevUnlocked
)
private
}
function _emitShareRateChange(uint256 shareRate, uint40 stakeId)
private
}
}
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
if (computedHash < proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
| 1,819,085
|
./partial_match/1/0xC22fF0D6584c5006b59a1f8C6f317Efa2Ad47D75/sources/Checkpoints.sol
|
Access an element of the array without performing bounds check. The position is assumed to be within bounds./
|
function _unsafeAccess(
Checkpoint224[] storage self,
uint256 pos
) private pure returns (Checkpoint224 storage result) {
assembly {
mstore(0, self.slot)
result.slot := add(keccak256(0, 0x20), pos)
}
}
| 2,826,583
|
./full_match/1/0x8C4ABFbFb81eEcC37313EBe8cc4e0a202637F675/sources/contracts/IPWrapper.sol
|
@inheritdoc NFAiGatewayInterface/
|
function getTotalStaked() external view returns (uint256){
return nFAiStakingLottery.getTotalStaked();
}
| 2,989,737
|
./full_match/1/0x65fff8F5f6a9922b6dC13fE06345a0Fe46Dd413D/sources/contracts/VFToken.sol
|
mint batch `to` for `quantity` starting at `startTokenId` Requirements: - the caller must be a minter role - minting must not be locked and must be active/
|
function mintBatch(
address to,
uint8 quantity,
uint256 startTokenId
)
external
onlyRoles(_controlContract.getMinterRoles())
notLocked
mintActive
{
_mintBatch(to, quantity, startTokenId);
}
| 4,972,471
|
./partial_match/3/0xBcc008d20736433605c6b61f185d3B605440Eb5f/sources/pool.sol
|
Returns the owner of this contract/
|
function owner() external override view returns (address) {
return _owner;
}
| 5,122,999
|
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/OrderCombiner.sol
|
Internal function to match an arbitrary number of full or partial orders, each with an arbitrary number of items for offer and consideration, supplying criteria resolvers containing specific token identifiers and associated proofs as well as fulfillments allocating offer components to consideration components. advancedOrders The advanced orders to match. Note that both the offerer and fulfiller on each order must first approve this contract (or their conduit if indicated by the order) to transfer any relevant tokens on their behalf and each consideration recipient must implement `onERC1155Received` in order to receive ERC1155 tokens. Also note that the offer and consideration components for each order must have no remainder after multiplying the respective amount with the supplied fraction in order for the group of partial fills to be considered valid. criteriaResolvers An array where each element contains a reference to a specific order as well as that order's offer or consideration, a token identifier, and a proof that the supplied token identifier is contained in the order's merkle root. Note that an empty root indicates that any (transferable) token identifier is valid and that no associated proof needs to be supplied. fulfillments An array of elements allocating offer components to consideration components. Note that each consideration component must be fully met in order for the match operation to be valid. recipient The intended recipient for all unspent offer item amounts. return executions An array of elements indicating the sequence of transfers performed as part of matching the given orders./ Validate orders, update order status, and determine item amounts. Emit OrdersMatched event, providing an array of matched order hashes. Fulfill the orders using the supplied fulfillments and recipient.
|
function _matchAdvancedOrders(
AdvancedOrder[] memory advancedOrders,
CriteriaResolver[] memory criteriaResolvers,
Fulfillment[] memory fulfillments,
address recipient
) internal returns (Execution[] memory /* executions */) {
bytes32[] memory orderHashes = _validateOrdersAndPrepareToFulfill(
advancedOrders,
criteriaResolvers,
advancedOrders.length,
recipient
);
_emitOrdersMatched(orderHashes);
return
_fulfillAdvancedOrders(
advancedOrders,
fulfillments,
orderHashes,
recipient
);
}
| 4,301,333
|
/*
Copyright 2018 Set Labs 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.4.24;
import { AddressArrayUtils } from "cryptofin-solidity/contracts/array-utils/AddressArrayUtils.sol";
import { DetailedERC20 } from "zeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol";
import { Math } from "zeppelin-solidity/contracts/math/Math.sol";
import { SafeMath } from "zeppelin-solidity/contracts/math/SafeMath.sol";
import { StandardToken } from "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol";
import { Bytes32 } from "../lib/Bytes32.sol";
import { CommonMath } from "../lib/CommonMath.sol";
import { ERC20Wrapper } from "../lib/ERC20Wrapper.sol";
import { IAuctionPriceCurve } from "./lib/auction-price-libraries/IAuctionPriceCurve.sol";
import { ICore } from "./interfaces/ICore.sol";
import { IRebalancingSetFactory } from "./interfaces/IRebalancingSetFactory.sol";
import { ISetToken } from "./interfaces/ISetToken.sol";
import { IVault } from "./interfaces/IVault.sol";
/**
* @title SetToken
* @author Set Protocol
*
* Implementation of Rebalancing Set token.
*/
contract RebalancingSetToken is
StandardToken,
DetailedERC20
{
using SafeMath for uint256;
using Bytes32 for bytes32;
using AddressArrayUtils for address[];
/* ============ Enums ============ */
enum State { Default, Proposal, Rebalance }
/* ============ State Variables ============ */
address public factory;
// All rebalancingSetTokens have same natural unit, still allows for
// small amounts to be issued and attempts to reduce slippage as much
// as possible.
uint256 public naturalUnit = 10 ** 10;
address public manager;
State public rebalanceState;
// State updated after every rebalance
address public currentSet;
uint256 public unitShares;
uint256 public lastRebalanceTimestamp;
// Fee setting, values in basis points
uint256 public entranceFee;
uint256 public rebalanceFee;
// State governing rebalance cycle
uint256 public proposalPeriod;
uint256 public rebalanceInterval;
// State to track proposal period
uint256 public proposalStartTime;
// State needed for auction/rebalance
uint256 public auctionStartTime;
address public nextSet;
address public auctionLibrary;
uint256 public auctionPriceDivisor;
uint256 public auctionStartPrice;
uint256 public minimumBid;
uint256 public curveCoefficient;
address[] public combinedTokenArray;
uint256[] public combinedCurrentUnits;
uint256[] public combinedNextSetUnits;
uint256 public remainingCurrentSets;
/* ============ Events ============ */
event NewManagerAdded(
address newManager,
address oldManager
);
event RebalanceProposed(
address nextSet,
address indexed auctionLibrary,
uint256 indexed proposalPeriodEndTime
);
event RebalanceStarted(
address oldSet,
address newSet
);
/* ============ Constructor ============ */
/**
* Constructor function for Rebalancing Set Token
*
*
* @param _factory Factory used to create the Rebalancing Set
* @param _manager Manager of the Rebalancing Set
* @param _initialSet Initial set that collateralizes the Rebalancing set
* @param _initialUnitShares Units of currentSet that equals one share
* @param _proposalPeriod Amount of time for users to inspect a rebalance proposal
* @param _rebalanceInterval Minimum amount of time between rebalances
* @param _entranceFee Entrance fee as a percentage of initialSet when minting the Rebalancing Set
* @param _rebalanceFee Rebalance fee as a percentage of the nextSet when rebalance is settled
* @param _name The bytes32 encoded name of the new RebalancingSetToken
* @param _symbol The bytes32 encoded symbol of the new RebalancingSetToken
*/
constructor(
address _factory,
address _manager,
address _initialSet,
uint256 _initialUnitShares,
uint256 _proposalPeriod,
uint256 _rebalanceInterval,
uint256 _entranceFee,
uint256 _rebalanceFee,
bytes32 _name,
bytes32 _symbol
)
public
DetailedERC20(
_name.bytes32ToString(),
_symbol.bytes32ToString(),
18
)
{
// Require initial unit shares is non-zero
require(_initialUnitShares > 0, "UNIT_SHARES_MUST_BE_NON_ZERO");
// Require manager address is non-zero
require(_manager != address(0), "MANAGER_MUST_BE_NON_NULL");
// Require minimum rebalance interval and proposal period from factory
IRebalancingSetFactory tokenFactory = IRebalancingSetFactory(_factory);
require(_proposalPeriod >= tokenFactory.minimumProposalPeriod(), "PROPOSAL_PERIOD_TOO_SHORT");
require(_rebalanceInterval >= tokenFactory.minimumRebalanceInterval(), "REBALANCE_INTERVAL_TOO_SHORT");
factory = _factory;
manager = _manager;
entranceFee = _entranceFee;
rebalanceFee = _rebalanceFee;
currentSet = _initialSet;
unitShares = _initialUnitShares;
proposalPeriod = _proposalPeriod;
rebalanceInterval = _rebalanceInterval;
lastRebalanceTimestamp = block.timestamp;
rebalanceState = State.Default;
}
/* ============ Public Functions ============ */
/**
* Function used to set the terms of the next rebalance and start the proposal period
*
*
* @param _nextSet The Set to rebalance into
* @param _auctionLibrary The library used to calculate the Dutch Auction price
* @param _curveCoefficient The slope (or convexity) of the price curve
* @param _auctionPriceDivisor The granularity with which the prices change
* @param _auctionStartPrice The price to start the auction at
*/
function propose(
address _nextSet,
address _auctionLibrary,
uint256 _curveCoefficient,
uint256 _auctionStartPrice,
uint256 _auctionPriceDivisor
)
external
{
ICore core = ICore(IRebalancingSetFactory(factory).core());
// Make sure it is manager that is proposing the rebalance
require(msg.sender == manager, "ONLY_MANAGER_CAN_PROPOSE");
// New proposal cannot be made during a rebalance period
require(rebalanceState != State.Rebalance, "PROPOSE_CALLED_DURING_REBALANCE");
// Make sure enough time has passed from last rebalance to start a new proposal
require(block.timestamp >= lastRebalanceTimestamp.add(rebalanceInterval), "PROPOSE_CALLED_TOO_EARLY");
// Check that new proposed Set is valid Set created by Core
require(core.validSets(_nextSet), "PROPOSED_SET_INVALID");
// Check that the auction library is a valid priceLibrary tracked by Core
require(core.validPriceLibraries(_auctionLibrary), "PRICE_LIB_MUST_BE_VALID");
// Assert price divisor is non-zero, ensuring a positive slope
require(_auctionPriceDivisor > 0, "PRICE_DIV_MUST_BE_NON_ZERO");
// Assert curve coefficient > 0, ensuring a positive slope
require(_curveCoefficient > 0, "CURVE_COEF_MUST_BE_NON_ZERO");
// Check that the propoosed set natural unit is a multiple of current set natural unit, or vice versa.
// Done to make sure that when calculating token units there will are no rounding errors.
uint256 currentNaturalUnit = ISetToken(currentSet).naturalUnit();
uint256 nextSetNaturalUnit = ISetToken(_nextSet).naturalUnit();
require(
Math.max256(currentNaturalUnit, nextSetNaturalUnit) %
Math.min256(currentNaturalUnit, nextSetNaturalUnit) == 0,
"SET_NATURAL_UNITS_NOT_MULTIPLES"
);
// Set auction parameters
nextSet = _nextSet;
auctionLibrary = _auctionLibrary;
curveCoefficient = _curveCoefficient;
auctionStartPrice = _auctionStartPrice;
auctionPriceDivisor = _auctionPriceDivisor;
// Update state parameters
proposalStartTime = block.timestamp;
rebalanceState = State.Proposal;
emit RebalanceProposed(
_nextSet,
_auctionLibrary,
proposalStartTime.add(proposalPeriod)
);
}
/*
* Initiate rebalance for the rebalancing set. Users can now submit bids.
*
*/
function rebalance()
external
{
// Must be in "Proposal" state before going into "Rebalance" state
require(rebalanceState == State.Proposal, "ONLY_CALLABLE_FROM_PROPOSE_STATE");
// Be sure the full proposal period has elapsed
require(block.timestamp >= proposalStartTime.add(proposalPeriod), "PROPOSAL_PERIOD_NOT_ELAPSED");
// Get core address from factory and create core interface
ICore core = ICore(IRebalancingSetFactory(factory).core());
// Create token arrays needed for auction
auctionSetUp();
// Get currentSet natural unit
uint256 currentSetNaturalUnit = ISetToken(currentSet).naturalUnit();
// Get remainingCurrentSets and make it divisible by currentSet natural unit
remainingCurrentSets = IVault(core.vault()).getOwnerBalance(
currentSet,
this
);
remainingCurrentSets = remainingCurrentSets.div(currentSetNaturalUnit).mul(currentSetNaturalUnit);
// Redeem current set held by rebalancing token in vault
core.redeemInVault(currentSet, remainingCurrentSets);
// Update state parameters
auctionStartTime = block.timestamp;
rebalanceState = State.Rebalance;
emit RebalanceStarted(currentSet, nextSet);
}
/*
* Initiate settlement for the rebalancing set. Full functionality now returned to
* set owners.
*
*/
function settleRebalance()
external
{
// Must be in Rebalance state to call settlement
require(rebalanceState == State.Rebalance, "NEED_ACTIVE_REBALANCE_TO_SETTLE");
// Make sure all currentSets have been rebalanced
require(remainingCurrentSets < minimumBid, "REBALANCE_NOT_FINISHED");
// Creating pointer to Core to Issue next set and Deposit into vault and to nextSet token
// to transfer fees
ICore core = ICore(IRebalancingSetFactory(factory).core());
ISetToken nextSetInstance = ISetToken(nextSet);
address protocolAddress = core.protocolAddress();
// Issue nextSet to RebalancingSetToken
uint256 issueAmount;
uint256 totalFees;
uint256 managerFee;
uint256 protocolFee;
(issueAmount, unitShares, totalFees) = calculateNextSetIssueQuantity();
(managerFee, protocolFee) = calculateFeeSplit(totalFees);
core.issue(
nextSet,
issueAmount
);
// Ensure transfer proxy has enough spender allowance to move issued nextSet to vault
ERC20Wrapper.ensureAllowance(
nextSet,
this,
core.transferProxy(),
issueAmount
);
// Deposit newly created nextSets in Vault
core.deposit(
nextSet,
issueAmount.sub(totalFees)
);
nextSetInstance.transfer(
manager,
managerFee
);
if (protocolFee > 0) {
nextSetInstance.transfer(
protocolAddress,
protocolFee
);
}
// Set current set to be rebalancing set
currentSet = nextSet;
// Update state parameters
lastRebalanceTimestamp = block.timestamp;
rebalanceState = State.Default;
}
/*
* Place bid during rebalance auction. Can only be called by Core.
*
* @param _quantity The amount of currentSet to be rebalanced
* @return combinedTokenArray Array of token addresses invovled in rebalancing
* @return inflowUnitArray Array of amount of tokens inserted into system in bid
* @return outflowUnitArray Array of amount of tokens taken out of system in bid
*/
function placeBid(
uint256 _quantity
)
external
returns (address[], uint256[], uint256[])
{
// Make sure sender is Core
require(msg.sender == IRebalancingSetFactory(factory).core(), "ONLY_CORE_CAN_PLACE_BID");
// Confirm in Rebalance State
require(rebalanceState == State.Rebalance, "NEED_ACTIVE_REBALANCE_TO_BID");
// Make sure that bid amount is multiple of minimum bid amount
require(_quantity % minimumBid == 0, "NOT_MINIMUM_BID_MULTIPLE");
// Make sure that bid Amount is less than remainingCurrentSets
require(_quantity <= remainingCurrentSets, "BID_SIZE_TOO_LARGE");
// Calculate token inflow and outflow arrays
uint256[] memory inflowUnitArray = new uint256[](combinedTokenArray.length);
uint256[] memory outflowUnitArray = new uint256[](combinedTokenArray.length);
(inflowUnitArray, outflowUnitArray) = getBidPrice(_quantity);
remainingCurrentSets = remainingCurrentSets.sub(_quantity);
return (combinedTokenArray, inflowUnitArray, outflowUnitArray);
}
/*
* Get token inflows and outflows required for bid. Also the amount of Rebalancing
* Sets that would be generated.
*
* @param _quantity The amount of currentSet to be rebalanced
* @return inflowUnitArray Array of amount of tokens inserted into system in bid
* @return outflowUnitArray Array of amount of tokens taken out of system in bid
*/
function getBidPrice(
uint256 _quantity
)
public
view
returns (uint256[], uint256[])
{
// Confirm in Rebalance State
require(rebalanceState == State.Rebalance, "NEED_ACTIVE_REBALANCE_TO_PRICE");
// Declare unit arrays in memory
uint256[] memory inflowUnitArray = new uint256[](combinedTokenArray.length);
uint256[] memory outflowUnitArray = new uint256[](combinedTokenArray.length);
// Get bid conversion price, currently static placeholder for calling auctionlibrary
uint256 priceNumerator = IAuctionPriceCurve(auctionLibrary).getCurrentPrice(
auctionStartTime,
auctionStartPrice,
curveCoefficient
);
// Normalized quantity amount
uint256 unitsMultiplier = _quantity.div(minimumBid).mul(auctionPriceDivisor);
for (uint256 i = 0; i < combinedTokenArray.length; i++) {
uint256 nextUnit = combinedNextSetUnits[i];
uint256 currentUnit = combinedCurrentUnits[i];
/*
* Below is a mathematically simplified formula for calculating token inflows and
* outflows, the following is it's derivation:
* token_flow = (bidQuantity/price)*(nextUnit - price*currentUnit)
*
* Where,
* 1) price = (priceNumerator/auctionPriceDivisor),
* 2) nextUnit and currentUnit are the amount of component i needed for a
* standardAmount of sets to be rebalanced where one standardAmount =
* max(natural unit nextSet, natural unit currentSet), and
* 3) bidQuantity is a normalized amount in terms of the standardAmount used
* to calculate nextUnit and currentUnit. This is represented by the unitsMultiplier
* variable.
*
* Given these definitions we can derive the below formula as follows:
* token_flow = (unitsMultiplier/(priceNumerator/auctionPriceDivisor))*
* (nextUnit - (priceNumerator/auctionPriceDivisor)*currentUnit)
*
* We can then multiply this equation by (auctionPriceDivisor/auctionPriceDivisor)
* which simplifies the above equation to:
*
* (unitsMultiplier/priceNumerator)* (nextUnit*auctionPriceDivisor - currentUnit*priceNumerator)
*
* This is the equation seen below, but since unsigned integers are used we must check to see if
* nextUnit*auctionPriceDivisor > currentUnit*priceNumerator, otherwise those two terms must be
* flipped in the equation.
*/
if (nextUnit.mul(auctionPriceDivisor) > currentUnit.mul(priceNumerator)) {
inflowUnitArray[i] = unitsMultiplier.mul(
nextUnit.mul(auctionPriceDivisor).sub(currentUnit.mul(priceNumerator))
).div(priceNumerator);
// Set outflow amount to 0 for component i, since tokens need to be injected in rebalance
outflowUnitArray[i] = 0;
} else {
// Calculate outflow amount
outflowUnitArray[i] = unitsMultiplier.mul(
currentUnit.mul(priceNumerator).sub(nextUnit.mul(auctionPriceDivisor))
).div(priceNumerator);
// Set inflow amount to 0 for component i, since tokens need to be returned in rebalance
inflowUnitArray[i] = 0;
}
}
return (inflowUnitArray, outflowUnitArray);
}
/*
* Mint set token for given address.
* Can only be called by Core contract.
*
* @param _issuer The address of the issuing account
* @param _quantity The number of sets to attribute to issuer
*/
function mint(
address _issuer,
uint256 _quantity
)
external
{
// Check that function caller is Core
require(msg.sender == IRebalancingSetFactory(factory).core(), "ONLY_CORE_CAN_MINT_REBAL_SET");
// Check that set is not in Rebalancing State
require(rebalanceState != State.Rebalance, "MINT_PAUSED_DURING_REBALANCE");
uint256 totalFees = _quantity.mul(entranceFee).div(10000);
uint256 issuerTotal = _quantity.sub(totalFees);
uint256 managerFee;
uint256 protocolFee;
(managerFee, protocolFee) = calculateFeeSplit(totalFees);
// Update token balance of the manager
balances[_issuer] = balances[_issuer].add(issuerTotal);
balances[manager] = balances[manager].add(managerFee);
if (protocolFee > 0) {
// Get protocol address and add fees to protocol and issuer
address protocolAddress = ICore(IRebalancingSetFactory(factory).core()).protocolAddress();
balances[protocolAddress] = balances[protocolAddress].add(protocolFee);
// Emit transfer log for protocol fee
emit Transfer(address(0), protocolAddress, protocolFee);
}
// Update the total supply of the set token
totalSupply_ = totalSupply_.add(_quantity);
// Emit a transfer log for issuer and manager fee
emit Transfer(address(0), _issuer, issuerTotal);
emit Transfer(address(0), manager, managerFee);
}
/*
* Burn set token for given address.
* Can only be called by authorized contracts.
*
* @param _from The address of the redeeming account
* @param _quantity The number of sets to burn from redeemer
*/
function burn(
address _from,
uint256 _quantity
)
external
{
// Check that function caller is Core
require(msg.sender == IRebalancingSetFactory(factory).core(), "ONLY_CORE_CAN_BURN_REBAL_SET");
// Check that set is not in Rebalancing State
require(rebalanceState != State.Rebalance, "BURN_PAUSED_DURING_REBALANCE");
// Require user has tokens to burn
require(balances[_from] >= _quantity, "NOT_ENOUGH_TOKENS_TO_BURN");
// Update token balance of user
balances[_from] = balances[_from].sub(_quantity);
// Update total supply of Set Token
totalSupply_ = totalSupply_.sub(_quantity);
// Emit a transfer log with to address being 0 indicating burn
emit Transfer(_from, address(0), _quantity);
}
/*
* Set new manager address
*
* @param _newManager The address of the redeeming account
*/
function setManager(
address _newManager
)
external
{
require(msg.sender == manager, "ONLY_MANAGER_CAN_SET");
emit NewManagerAdded(_newManager, manager);
manager = _newManager;
}
/* ============ Getter Functions ============ */
/*
* Get addresses of setToken underlying the Rebalancing Set
*
* @return componentAddresses Array of currentSet
*/
function getComponents()
external
view
returns(address[])
{
address[] memory components = new address[](1);
components[0] = currentSet;
return components;
}
/*
* Get unitShares of Rebalancing Set
*
* @return units Array of component unit
*/
function getUnits()
external
view
returns(uint256[])
{
uint256[] memory units = new uint256[](1);
units[0] = unitShares;
return units;
}
/*
* Get combinedTokenArray of Rebalancing Set
*
* @return combinedTokenArray
*/
function getCombinedTokenArrayLength()
external
view
returns(uint256)
{
return combinedTokenArray.length;
}
/*
* Get combinedTokenArray of Rebalancing Set
*
* @return combinedTokenArray
*/
function getCombinedTokenArray()
external
view
returns(address[])
{
return combinedTokenArray;
}
/*
* Get combinedCurrentUnits of Rebalancing Set
*
* @return combinedCurrentUnits
*/
function getCombinedCurrentUnits()
external
view
returns(uint256[])
{
return combinedCurrentUnits;
}
/*
* Get combinedNextSetUnits of Rebalancing Set
*
* @return combinedNextSetUnits
*/
function getCombinedNextSetUnits()
external
view
returns(uint256[])
{
return combinedNextSetUnits;
}
/* ============ Internal Functions ============ */
/**
* Create array that represents all components in currentSet and nextSet.
* Calcualate unit difference between both sets relative to the largest natural
* unit of the two sets.
*/
function auctionSetUp()
private
{
// Create interfaces for interacting with sets
ISetToken currentSetInstance = ISetToken(currentSet);
ISetToken nextSetInstance = ISetToken(nextSet);
// Create combined token Array
address[] memory oldComponents = currentSetInstance.getComponents();
address[] memory newComponents = nextSetInstance.getComponents();
combinedTokenArray = oldComponents.union(newComponents);
// Get naturalUnit of both sets
uint256 currentSetNaturalUnit = currentSetInstance.naturalUnit();
uint256 nextSetNaturalUnit = nextSetInstance.naturalUnit();
// Get units arrays for both sets
uint256[] memory currentSetUnits = currentSetInstance.getUnits();
uint256[] memory nextSetUnits = nextSetInstance.getUnits();
// Create memory version of combinedNextSetUnits and combinedCurrentUnits to only make one
// call to storage once arrays have been created
uint256[] memory memoryCombinedCurrentUnits = new uint256[](combinedTokenArray.length);
uint256[] memory memoryCombinedNextSetUnits = new uint256[](combinedTokenArray.length);
minimumBid = Math.max256(
currentSetNaturalUnit.mul(auctionPriceDivisor),
nextSetNaturalUnit.mul(auctionPriceDivisor)
);
for (uint256 i=0; i < combinedTokenArray.length; i++) {
// Check if component in arrays and get index if it is
(uint256 indexCurrent, bool isInCurrent) = oldComponents.indexOf(combinedTokenArray[i]);
(uint256 indexRebalance, bool isInNext) = newComponents.indexOf(combinedTokenArray[i]);
// Compute and push unit amounts of token in currentSet, push 0 if not in set
if (isInCurrent) {
memoryCombinedCurrentUnits[i] = computeUnits(currentSetUnits[indexCurrent], currentSetNaturalUnit);
} else {
memoryCombinedCurrentUnits[i] = uint256(0);
}
// Compute and push unit amounts of token in nextSet, push 0 if not in set
if (isInNext) {
memoryCombinedNextSetUnits[i] = computeUnits(nextSetUnits[indexRebalance], nextSetNaturalUnit);
} else {
memoryCombinedNextSetUnits[i] = uint256(0);
}
}
// Set combinedCurrentUnits and combinedNextSetUnits to memory versions of arrays
combinedCurrentUnits = memoryCombinedCurrentUnits;
combinedNextSetUnits = memoryCombinedNextSetUnits;
}
/**
* Calculate the amount of nextSets to issue by using the component amounts in the
* vault, unitShares following from this calculation.
* @return uint256 Amount of nextSets to issue
* @return uint256 New unitShares for the rebalancingSetToken
*/
function calculateNextSetIssueQuantity()
private
returns (uint256, uint256, uint256)
{
// Collect data necessary to compute issueAmounts
uint256 nextNaturalUnit = ISetToken(nextSet).naturalUnit();
address[] memory nextComponents = ISetToken(nextSet).getComponents();
uint256[] memory nextUnits = ISetToken(nextSet).getUnits();
uint256 maxIssueAmount = CommonMath.maxUInt256();
// Set up vault interface
address vaultAddress = ICore(IRebalancingSetFactory(factory).core()).vault();
IVault vault = IVault(vaultAddress);
for (uint256 i = 0; i < nextComponents.length; i++) {
// Get amount of components in vault owned by rebalancingSetToken
uint256 componentAmount = vault.getOwnerBalance(
nextComponents[i],
this
);
// Calculate amount of Sets that can be issued from those components, if less than amount for other
// components then set that as maxIssueAmount
uint256 componentIssueAmount = componentAmount.div(nextUnits[i]).mul(nextNaturalUnit);
if (componentIssueAmount < maxIssueAmount) {
maxIssueAmount = componentIssueAmount;
}
}
// Calculate the amount of naturalUnits worth of rebalancingSetToken outstanding
uint256 naturalUnitsOutstanding = totalSupply_.div(naturalUnit);
// Issue amount of Sets that is closest multiple of nextNaturalUnit to the maxIssueAmount
// Since the initial division will round down to the nearest whole number when we multiply
// by that same number we will return the closest multiple less than the maxIssueAmount
uint256 issueAmount = maxIssueAmount.div(nextNaturalUnit).mul(nextNaturalUnit);
uint256 totalFees = issueAmount.mul(rebalanceFee).div(10000);
// Divide final issueAmount by naturalUnitsOutstanding to get newUnitShares
uint256 newUnitShares = issueAmount.sub(totalFees).div(naturalUnitsOutstanding);
return (issueAmount, newUnitShares, totalFees);
}
/**
* Function to calculate the transfer value of a component given 1 Set
*
* @param _unit The units of the component token
* @param _naturalUnit The natural unit of the Set token
* @return uint256 Amount of tokens per minimumBid/auctionPriceDivisor
*/
function computeUnits(
uint256 _unit,
uint256 _naturalUnit
)
private
returns (uint256)
{
return minimumBid.mul(_unit).div(_naturalUnit).div(auctionPriceDivisor);
}
/**
* Function to calculate splitting fees between manager and protocol
*
* @param totalFees Total amount of fees to split up
* @return uint256 Amount of tokens to send to manager
* @return uint256 Amount of tokens to send to protocol
*/
function calculateFeeSplit(
uint256 totalFees
)
private
returns (uint256, uint256)
{
uint256 protocolFee = totalFees.mul(ICore(IRebalancingSetFactory(factory).core()).protocolFee())
.div(10000);
uint256 managerFee = totalFees.sub(protocolFee);
return (managerFee, protocolFee);
}
}
|
Set new manager address _newManager The address of the redeeming account/
|
function setManager(
address _newManager
)
external
{
require(msg.sender == manager, "ONLY_MANAGER_CAN_SET");
emit NewManagerAdded(_newManager, manager);
manager = _newManager;
}
| 13,031,652
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract CyberBearz is ERC721, Ownable {
using SafeMath for uint256;
uint256 public constant BEARS_CAP = 2222;
bool public hasSaleStarted = false;
mapping (uint256 => string) private cyberBearsNames;
constructor(string memory myBase) ERC721("CYBERBEARZ", "CBRBRZ") {
_setBaseURI(myBase);
}
modifier isOwnerOfCyberBear(uint _tokenId) {
require(msg.sender == ownerOf(_tokenId), "You do not own this CyberBear");
_;
}
/**
* @dev CyberBears reactor
*/
function getCyberBear(uint256 _numOfCyberBears)
public
payable
{
require(totalSupply() < BEARS_CAP, "All CyberBears are already ownd");
require(_numOfCyberBears > 0 && _numOfCyberBears <= 10, "Min 1. Max 10");
require(totalSupply().add(_numOfCyberBears) <= BEARS_CAP, "Exceeds Capacity, grab less, please");
require(msg.value >= getCyberBearPrice().mul(_numOfCyberBears), "You havent sent enough eth");
for (uint256 i = 0; i < _numOfCyberBears; i++) {
uint mintIndex = totalSupply().add(1); //we start from tokenId = 1, not from 0
_safeMint(msg.sender, mintIndex);
}
}
/**
* @dev sets name for bear
*/
function setCyberBearName(uint256 _tokenId, string memory _cyberBearName) public isOwnerOfCyberBear(_tokenId) {
cyberBearsNames[_tokenId] = _cyberBearName;
}
/**
* @dev returns name
*/
function getCyberBearName(uint256 _tokenId) public view returns(string memory) {
return cyberBearsNames[_tokenId];
}
/**
* @dev sets new base URI in case old is broken
*/
function _setNewBaseURI(string memory _newBaseURI) external onlyOwner {
_setBaseURI(_newBaseURI);
}
function startDrop() public onlyOwner {
hasSaleStarted = true;
}
function pauseDrop() public onlyOwner {
hasSaleStarted = false;
}
/**
* @dev Returns current CyberBear price.
*/
function getCyberBearPrice() public view returns (uint256) {
require(hasSaleStarted == true, "Sale hasnt started");
require(totalSupply() < BEARS_CAP, "All CyberBears are already owned");
uint currentSupply = totalSupply();
if (currentSupply >= 2200) {
return 2000000000000000000; // last 2 Bearz = 2 ETH
} else {
return ( 1+ (currentSupply / 222)) * 2 * (10 ** 16); // each 222 bearz price increases 0,02 eth
}
}
/**
* @dev Withdraw ether from this contract
*/
function withdraw() onlyOwner public {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
/**
* @dev Admin key
*/
function giveCyberBear(address _toAddress) onlyOwner
public
{
require(totalSupply() < BEARS_CAP, "All CyberBears are already grabbed");
uint mintIndex = totalSupply().add(1); //we start from tokenId = 1, not from 0
_safeMint(_toAddress, mintIndex);
}
function setCyberBearNameAdmin(uint256 _tokenId, string memory _cyberBearName) public onlyOwner {
cyberBearsNames[_tokenId] = _cyberBearName;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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;
}
}
// 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.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Withdraw ether from this contract/
|
function withdraw() onlyOwner public {
uint256 balance = address(this).balance;
msg.sender.transfer(balance);
}
| 637,901
|
./full_match/1313161554/0x0617104180d049D2dda1349C6Aaad27087DD8A70/sources/bastion-protocol/contracts/Oracle/NEAROracle.sol
|
The price of cNEAR, which will return a constant 1e12 (NEAR is 24 decimals) and all prices will be relative to NEAR
|
function getUnderlyingPrice(CToken cToken) public view returns (uint) {
string memory symbol = cToken.symbol();
if (compareStrings(symbol, "cNEAR")) {
return 1e12;
return getPrice(cToken);
}
}
| 13,235,638
|
./partial_match/1/0x0eEf5D48a8032f263183d70F004fC74e68Ec1DED/sources/Balance.sol
|
销毁 @payer 的 QIAN, 并且增加相应的 @reserve 记录给 @payer, 同时 @who 减少相应的记录.
|
function exchange(
address payer,
address owner,
address token,
uint256 supply,
uint256 reserve
) public onlyOwner {
swaps[owner][token].supply = swaps[owner][token].supply.sub(supply);
gswaps[token].supply = gswaps[token].supply.sub(supply);
gsupply = gsupply.sub(supply);
swaps[owner][token].reserve = swaps[owner][token].reserve.sub(reserve);
swaps[payer][token].reserve = swaps[payer][token].reserve.add(reserve);
}
| 4,292,188
|
./full_match/1/0xEbE1645A82ecEfA9375F6E329f5ce664864981FA/sources/contracts/MerkleTwoDrop.sol
|
Award from airdrop _id Airdrop id _recipient Recepient of award _amount0 The token0 amount _amount1 The token1 amount _proof Merkle proof to correspond to data supplied/
|
function award(uint _id, address _recipient, uint256 _amount0, uint256 _amount1, bytes32[] calldata _proof) public {
Airdrop storage airdrop = airdrops[_id];
bytes32 hash = keccak256(abi.encodePacked(_recipient, _amount0, _amount1));
require( validate(airdrop.root, _proof, hash), "Invalid proof" );
require( !airdrops[_id].awarded[_recipient], "Already awarded" );
airdrops[_id].awarded[_recipient] = true;
tokenManager0.mint(_recipient, _amount0);
tokenManager1.mint(_recipient, _amount1);
emit Award(_id, _recipient, _amount0, _amount1);
}
| 3,171,795
|
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./Utilities/contracts/token/BEP20/IBEP20.sol";
import "./Utilities/contracts/utils/EnumerableSet.sol";
import "./Utilities/contracts/token/BEP20/SafeBEP20.sol";
import "./Utilities//contracts/math/SafeMath.sol";
import "./Utilities//contracts/access/Ownable.sol";
import "./Utilities//contracts/utils/ReentrancyGuard.sol";
contract DYNXTVault is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
uint256 internal constant RATE_NOMINATOR = 10000; // rate nominator
struct LockInfo {
uint256 lockId;
uint256 minimumDeposit;
uint256 percentage;
uint256 duration;
bool isEnabled;
}
struct StakeTracker {
uint256[] stakes;
uint256[] rewards;
uint256[] claimedAt;
uint256[] stakedAt;
uint256[] lockId;
}
// Whether it is initialized
bool public isInitialized;
// The reward token
IBEP20 public rewardToken;
// The staked token
IBEP20 public stakedToken;
//total staking tokens
uint256 public totalStakingTokens;
//total reward tokens
uint256 public totalRewardTokens;
uint256 public lockId;
mapping(uint256 => LockInfo) public lockInfo;
mapping(address => mapping(uint256 => StakeTracker)) private accounts;
mapping(address => bool) compound;
event AdminTokenRecovery(address tokenRecovered, uint256 amount);
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
event AddRewardTokens(address indexed user, uint256 amount);
event Harvest(address indexed user, uint reward);
/**
* @notice Initialize the contract
* @param _stakedToken: staked token address
* @param _rewardToken: reward token address
*/
function initialize(
IBEP20 _stakedToken,
IBEP20 _rewardToken
) external onlyOwner {
require(!isInitialized, "Already initialized");
// Make this contract initialized
isInitialized = true;
stakedToken = _stakedToken;
rewardToken = _rewardToken;
}
/**
* @dev get compound value against a user
* @param _user address of user
*/
function getUserCompund(address _user) external view returns(bool){
return compound[_user];
}
/**
* @dev get lock against id
* @param _lockId lock id
*/
function getLock(uint256 _lockId) external view returns (uint256, uint256, uint256, uint256, bool ){
LockInfo memory lock = lockInfo[_lockId];
return (lock.lockId, lock.minimumDeposit, lock.percentage, lock.duration, lock.isEnabled);
}
/**
* @dev user can set compound value to true and false, on havest value will be automatically send to investment
* @param _compound compound value
*/
function setCompound(bool _compound) external {
compound[msg.sender] = _compound;
}
/**
* @dev add or update locks
* @param _lockId add new lock id, send 0 for for new lock and lockId to update
* @param _minimumDeposit add minimum Deposit
* @param _percentage add percentage
* @param _duration duration of locks in blocks
* @param _isEnabled enable or disable lock
*/
function addOrUpdateLock(uint256 _lockId, uint256 _minimumDeposit, uint256 _percentage, uint256 _duration, bool _isEnabled) external onlyOwner {
//insert
if(_lockId == 0) {
lockId = lockId + 1;
lockInfo[lockId] = LockInfo(lockId, _minimumDeposit, _percentage, _duration, _isEnabled);
}else {
LockInfo storage info = lockInfo[_lockId];
info.minimumDeposit = _minimumDeposit;
info.percentage = _percentage;
info.duration = _duration;
info.isEnabled = _isEnabled;
}
}
/**
* @dev Deposit staked tokens and collect reward tokens (if any)
* @param _amount: amount to withdraw (in rewardToken)
* @param _lockId lockId where user needs to deposit
*/
function deposit(uint256 _amount, uint256 _lockId) external nonReentrant {
LockInfo memory lock = lockInfo[_lockId];
require(_amount >= lock.minimumDeposit, "amount should be greater than minimum Deposit");
StakeTracker storage account = accounts[msg.sender][_lockId];
account.stakes.push(_amount);
account.stakedAt.push(block.number);
account.claimedAt.push(block.number);
account.rewards.push(0);
account.lockId.push(_lockId);
stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount);
totalStakingTokens = totalStakingTokens.add(_amount);
emit Deposit(msg.sender, _amount);
}
/**
* @notice Withdraw staked tokens and collect reward tokens
* @param _amount: amount to withdraw (in rewardToken)
* @param _lockId: lock id
* @param _index index of the investment
*/
function withdraw(uint256 _amount, uint256 _lockId, uint256 _index) public nonReentrant {
StakeTracker storage account = accounts[msg.sender][_lockId];
LockInfo memory lock = lockInfo[_lockId];
require(_lockId == account.lockId[_index], "wrong lock id");
require(account.stakes[_index] >= _amount, "withdraw amount must not more than staked amount");
require(account.stakedAt[_index].add(lock.duration) < block.number, "unable to withdraw before the timelock");
uint256 reward = rewardOf(msg.sender, _lockId, _index);
account.stakes[_index] = account.stakes[_index].sub(_amount);
account.rewards[_index] = 0;
account.claimedAt[_index] = block.number;
//transfer stake tokens
stakedToken.safeTransfer(msg.sender, _amount);
totalStakingTokens = totalStakingTokens.sub(_amount);
//transfer pending reward
_safeRewardTransfer(msg.sender, reward);
emit Withdraw(msg.sender, _amount);
}
/**
* @dev withdraw all the rewards
* @param _lockId lock id
* @param _index investment id of the rewards
*/
function withdrawAll(uint256 _lockId, uint256 _index) external {
StakeTracker storage account = accounts[msg.sender][_lockId];
withdraw(account.stakes[_index], _lockId, _index);
}
/**
* @dev claim all funds
*/
function harvestAll() external {
for (uint256 i; i < lockId; i++) {
uint256[] memory rewards = rewardsOfLockId(msg.sender, i+1);
for(uint j; j < rewards.length; j++){
harvest(i+1, j);
}
}
}
/**
* @dev harvest token against lock id
* @param _lockId lock id
* @param _index investment index
*/
function harvest(uint256 _lockId, uint256 _index) public {
uint reward = rewardOf(msg.sender, _lockId, _index);
require(reward > 0, "insufficient rewards");
StakeTracker storage account = accounts[msg.sender][_lockId];
account.rewards[_index] = 0;
account.claimedAt[_index] = block.number;
if(compound[msg.sender] == true) {
account.stakes[_index] = account.stakes[_index] + reward;
totalStakingTokens = totalStakingTokens.add(reward);
}else{
_safeRewardTransfer(msg.sender, reward);
}
emit Harvest(msg.sender, reward);
}
/**
* @dev calculate rewards
* @param _address user address
* @param _lockId lock id
* @param _index investment index
*/
function rewardOf(address _address, uint256 _lockId, uint256 _index) public view returns (uint256) {
StakeTracker memory account = accounts[_address][_lockId];
LockInfo memory lock = lockInfo[_lockId];
uint256 accumulator = block.number > account.stakedAt[_index] + lock.duration ?
(account.stakedAt[_index] + lock.duration).sub(account.claimedAt[_index]):
block.number.sub(account.claimedAt[_index]);
uint reward = account.stakes[_index]
.mul(accumulator)
.mul(lock.percentage)
.div(RATE_NOMINATOR);
return account.rewards[_index].add(reward);
}
function rewardsOfLockId(address _address, uint256 _lockId) public view returns (uint256[] memory) {
uint256 length = accounts[_address][_lockId].rewards.length;
uint256[] memory rewards = new uint[](length);
for(uint i=0;i <length; i++) {
rewards[i] = rewardOf(_address, _lockId, i);
}
return rewards;
}
/**
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _user) external view returns (uint256) {
uint256 reward;
for (uint256 i = 0; i < lockId; i++) {
uint256[] memory rewards = rewardsOfLockId(_user, i + 1);
for(uint j; j < rewards.length; j++){
reward = reward.add(rewards[j]);
}
}
return reward;
}
/**
* @notice emergency withdraw all tokens
* @dev Only callable by owner. Needs to be for emergency.
*/
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
totalRewardTokens = totalRewardTokens.sub(_amount);
rewardToken.safeTransfer(address(msg.sender), _amount);
}
/**
* @notice It allows the admin to reward tokens
* @param _amount: amount of tokens
* @dev This function is only callable by admin.
*/
function addRewardTokens(uint256 _amount) external onlyOwner {
totalRewardTokens = totalRewardTokens.add(_amount);
rewardToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit AddRewardTokens(msg.sender, _amount);
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of tokens to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(stakedToken), "Cannot be staked token");
require(_tokenAddress != address(rewardToken), "Cannot be reward token");
IBEP20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
function getStakingAmount(address _user, uint256 _lockId, uint256 _index) external view returns(uint) {
StakeTracker memory account = accounts[_user][_lockId];
return account.stakes[_index];
}
/**
* @notice transfer reward tokens.
* @param _to: address where tokens will transfer
* @param _amount: amount of tokens
*/
function _safeRewardTransfer(address _to, uint256 _amount) internal {
uint256 rewardTokenBal = totalRewardTokens;
if (_amount > rewardTokenBal) {
totalRewardTokens = totalRewardTokens.sub(rewardTokenBal);
rewardToken.safeTransfer(_to, rewardTokenBal);
} else {
totalRewardTokens = totalRewardTokens.sub(_amount);
rewardToken.safeTransfer(_to, _amount);
}
}
}
|
withdraw all the rewards _lockId lock id _index investment id of the rewards/
|
function withdrawAll(uint256 _lockId, uint256 _index) external {
StakeTracker storage account = accounts[msg.sender][_lockId];
withdraw(account.stakes[_index], _lockId, _index);
}
| 14,114,055
|
pragma solidity ^0.4.13;
library CertsLib {
struct SignatureData {
/*
* status == 0x0 => UNKNOWN
* status == 0x1 => PENDING
* status == 0x2 => SIGNED
* Otherwise => Purpose (sha-256 of data)
*/
bytes32 status;
uint exp; // Expiration Date
}
struct TransferData {
address newOwner;
uint newEntityId;
}
struct CertData {
/*
* owner == 0 => POE_CERTIFICATE
* owner != 0 => PROPIETARY_CERTIFICATE
*/
address owner; // owner of the certificate (in case of being a peer)
uint entityId; // owner of the certificate (in case of being an entity)
bytes32 certHash; // sha256 checksum of the certificate JSON data
string ipfsCertHash; // ipfs multihash address of certificate in json format
bytes32 dataHash; // sha256 hash of certified data
string ipfsDataHash; // ipfs multihash address of certified data
mapping(uint => SignatureData) entities; // signatures from signing entities and their expiration date
uint[] entitiesArr;
mapping(address => SignatureData) signatures; // signatures from peers and their expiration date
address[] signaturesArr;
}
struct Data {
mapping(uint => CertData) certificates;
mapping(uint => TransferData) transferRequests;
uint nCerts;
}
// METHODS
/**
* Creates a new POE certificate
* @param self {object} - The data containing the certificate mappings
* @param dataHash {bytes32} - The hash of the certified data
* @param certHash {bytes32} - The sha256 hash of the json certificate
* @param ipfsDataHash {string} - The ipfs multihash address of the data (0x00 means unkwon)
* @param ipfsCertHash {string} - The ipfs multihash address of the certificate in json format (0x00 means unkwon)
* @return The id of the created certificate
*/
function createPOECertificate(Data storage self, bytes32 dataHash, bytes32 certHash, string ipfsDataHash, string ipfsCertHash) public returns (uint) {
require (hasData(dataHash, certHash, ipfsDataHash, ipfsCertHash));
uint certId = ++self.nCerts;
self.certificates[certId] = CertData({
owner: 0,
entityId: 0,
certHash: certHash,
ipfsCertHash: ipfsCertHash,
dataHash: dataHash,
ipfsDataHash: ipfsDataHash,
entitiesArr: new uint[](0),
signaturesArr: new address[](0)
});
POECertificate(certId);
return certId;
}
/**
* Creates a new certificate (with known owner). The owner will be the sender unless the entityId (issuer) is supplied.
* @param self {object} - The data containing the certificate mappings
* @param ed {object} - The data containing the entity mappings
* @param dataHash {bytes32} - The hash of the certified data
* @param certHash {bytes32} - The sha256 hash of the json certificate
* @param ipfsDataHash {string} - The ipfs multihash address of the data (0x00 means unkwon)
* @param ipfsCertHash {string} - The ipfs multihash address of the certificate in json format (0x00 means unkwon)
* @param entityId {uint} - The entity id which issues the certificate (0 if not issued by an entity)
* @return {uint} The id of the created certificate
*/
function createCertificate(Data storage self, EntityLib.Data storage ed, bytes32 dataHash, bytes32 certHash, string ipfsDataHash, string ipfsCertHash, uint entityId) senderCanIssueEntityCerts(ed, entityId) public returns (uint) {
require (hasData(dataHash, certHash, ipfsDataHash, ipfsCertHash));
uint certId = ++self.nCerts;
self.certificates[certId] = CertData({
owner: entityId == 0 ? msg.sender : 0,
entityId: entityId,
certHash: certHash,
ipfsCertHash: ipfsCertHash,
dataHash: dataHash,
ipfsDataHash: ipfsDataHash,
entitiesArr: new uint[](0),
signaturesArr: new address[](0)
});
Certificate(certId);
return certId;
}
/**
* Transfers a certificate owner. The owner can be a peer or an entity (never both), so only one of newOwner or newEntity must be different than 0.
* If the specified certificateId belongs to an entity, the msg.sender must be a valid signer for the entity. Otherwise the msg.sender must be the current owner.
* @param self {object} - The data containing the certificate mappings
* @param ed {object} - The data containing the entity mappings
* @param certificateId {uint} - The id of the certificate to transfer
* @param newOwner {address} - The address of the new owner
*/
function requestCertificateTransferToPeer(Data storage self, EntityLib.Data storage ed, uint certificateId, address newOwner) canTransferCertificate(self, ed, certificateId) public {
self.transferRequests[certificateId] = TransferData({
newOwner: newOwner,
newEntityId: 0
});
CertificateTransferRequestedToPeer(certificateId, newOwner);
}
/**
* Transfers a certificate owner. The owner can be a peer or an entity (never both), so only one of newOwner or newEntity must be different than 0.
* If the specified certificateId belongs to an entity, the msg.sender must be a valid signer for the entity. Otherwise the msg.sender must be the current owner.
* @param self {object} - The data containing the certificate mappings
* @param ed {object} - The data containing the entity mappings
* @param certificateId {uint} - The id of the certificate to transfer
* @param newEntityId {uint} - The id of the new entity
*/
function requestCertificateTransferToEntity(Data storage self, EntityLib.Data storage ed, uint certificateId, uint newEntityId) entityExists(ed, newEntityId) canTransferCertificate(self, ed, certificateId) public {
self.transferRequests[certificateId] = TransferData({
newOwner: 0,
newEntityId: newEntityId
});
CertificateTransferRequestedToEntity(certificateId, newEntityId);
}
/**
* Accept the certificate transfer
* @param self {object} - The data containing the certificate mappings
* @param ed {object} - The data containing the entity mappings
* @param certificateId {uint} - The id of the certificate to transfer
*/
function acceptCertificateTransfer(Data storage self, EntityLib.Data storage ed, uint certificateId) canAcceptTransfer(self, ed, certificateId) public {
TransferData storage reqData = self.transferRequests[certificateId];
self.certificates[certificateId].owner = reqData.newOwner;
self.certificates[certificateId].entityId = reqData.newEntityId;
CertificateTransferAccepted(certificateId, reqData.newOwner, reqData.newEntityId);
delete self.transferRequests[certificateId];
}
/**
* Cancel any certificate transfer request
* @param self {object} - The data containing the certificate mappings
* @param ed {object} - The data containing the entity mappings
* @param certificateId {uint} - The id of the certificate to transfer
*/
function cancelCertificateTransfer(Data storage self, EntityLib.Data storage ed, uint certificateId) canTransferCertificate(self, ed, certificateId) public {
self.transferRequests[certificateId] = TransferData({
newOwner: 0,
newEntityId: 0
});
CertificateTransferCancelled(certificateId);
}
/**
* Updates ipfs multihashes of a particular certificate
* @param self {object} - The data containing the certificate mappings
* @param certId {uint} - The id of the certificate
* @param ipfsDataHash {string} - The ipfs multihash address of the data (0x00 means unkwon)
* @param ipfsCertHash {string} - The ipfs multihash address of the certificate in json format (0x00 means unkwon)
*/
function setIPFSData(Data storage self, uint certId, string ipfsDataHash, string ipfsCertHash) ownsCertificate(self, certId) public {
self.certificates[certId].ipfsDataHash = ipfsDataHash;
self.certificates[certId].ipfsCertHash = ipfsCertHash;
UpdatedIPFSData(certId);
}
// HELPERS
/**
* Returns true if the certificate has valid data
* @param dataHash {bytes32} - The hash of the certified data
* @param certHash {bytes32} - The sha256 hash of the json certificate
* @param ipfsDataHash {string} - The ipfs multihash address of the data (0x00 means unkwon)
* @param ipfsCertHash {string} - The ipfs multihash address of the certificate in json format (0x00 means unkwon) * @return {bool} - True if the certificate contains valid data
*/
function hasData(bytes32 dataHash, bytes32 certHash, string ipfsDataHash, string ipfsCertHash) pure public returns (bool) {
return certHash != 0
|| dataHash != 0
|| bytes(ipfsDataHash).length != 0
|| bytes(ipfsCertHash).length != 0;
}
// MODIFIERS
/**
* Returns True if msg.sender is the owner of the specified certificate. False otherwise.
* @param self {object} - The data containing the certificate mappings
* @param id {uint} - The id of the certificate
*/
modifier ownsCertificate(Data storage self, uint id) {
require (self.certificates[id].owner == msg.sender);
_;
}
/**
* Returns TRUE if the specified entity is valid and the sender is a valid signer from the entity.
* If the entityId is 0 (not provided), it also returns TRUE
* @param ed {object} - The data containing the entity mappings
* @param entityId {uint} - The entityId which will issue the certificate
*/
modifier senderCanIssueEntityCerts(EntityLib.Data storage ed, uint entityId) {
require (entityId == 0
|| (EntityLib.isValid(ed, entityId) && ed.entities[entityId].signers[msg.sender].status == 2));
_;
}
/**
* Returns TRUE if the certificate has data and can be transfered to the new owner:
* - When the certificate is owned by a peer: the sender must be the owner of the certificate
* - When the certificate belongs to an entity: the entity must be valid
* AND the signer must be a valid signer of the entity
* @param self {object} - The data containing the certificate mappings
* @param ed {object} - The data containing the entity mappings
* @param certificateId {uint} - The certificateId which transfer is required
*/
modifier canTransferCertificate(Data storage self, EntityLib.Data storage ed, uint certificateId) {
CertData storage cert = self.certificates[certificateId];
require (hasData(cert.dataHash, cert.certHash, cert.ipfsDataHash, cert.ipfsCertHash));
if (cert.owner != 0) {
require (cert.owner == msg.sender);
_;
} else if (cert.entityId != 0) {
EntityLib.EntityData storage entity = ed.entities[cert.entityId];
require (EntityLib.isValid(ed, cert.entityId) && entity.signers[msg.sender].status == 2);
_;
}
}
/**
* Returns TRUE if the entity exists
*/
modifier entityExists(EntityLib.Data storage ed, uint entityId) {
require (EntityLib.exists(ed, entityId));
_;
}
/**
* Returns TRUE if the msg.sender can accept the certificate transfer
* @param self {object} - The data containing the certificate mappings
* @param ed {object} - The data containing the entity mappings
* @param certificateId {uint} - The certificateId which transfer is required
*/
modifier canAcceptTransfer(Data storage self, EntityLib.Data storage ed, uint certificateId) {
CertData storage cert = self.certificates[certificateId];
require (hasData(cert.dataHash, cert.certHash, cert.ipfsDataHash, cert.ipfsCertHash));
TransferData storage reqData = self.transferRequests[certificateId];
require(reqData.newEntityId != 0 || reqData.newOwner != 0);
if (reqData.newOwner == msg.sender) {
_;
} else if (reqData.newEntityId != 0) {
EntityLib.EntityData storage newEntity = ed.entities[reqData.newEntityId];
require (EntityLib.isValid(ed, reqData.newEntityId) && newEntity.signers[msg.sender].status == 2);
_;
}
}
// EVENTS
event POECertificate(uint indexed certificateId);
event Certificate(uint indexed certificateId);
event CertificateTransferRequestedToPeer(uint indexed certificateId, address newOwner);
event CertificateTransferRequestedToEntity(uint indexed certificateId, uint newEntityId);
event CertificateTransferAccepted(uint indexed certificateId, address newOwner, uint newEntityId);
event CertificateTransferCancelled(uint indexed certificateId);
event UpdatedIPFSData(uint indexed certificateId);
}
library EntityLib {
struct SignerData {
string signerDataHash;
/*
* status == 0 => NOT_VALID
* status == 1 => VALIDATION_PENDING
* status == 2 => VALID
* status == 3 => DATA_UPDATED
*/
uint status;
}
struct EntityData {
address owner;
string dataHash; // hash entity data
/*
* status == 0 => NOT_VALID
* status == 1 => VALIDATION_PENDING
* status == 2 => VALID
* status == 4 => RENEWAL_REQUESTED
* status == 8 => CLOSED
* otherwise => UNKNOWN
*/
uint status;
bytes32 urlHash; // hash url only
uint expiration; // Expiration date
uint renewalPeriod; // Renewal period to be used for 3rd party renewals (3rd party paying the validation expenses)
bytes32 oraclizeQueryId; // Last query Id from oraclize. We will only process the last request
/*
* signers[a] == 0;
* signers[a] = ipfs multihash address for signer data file in json format
*/
mapping(address => SignerData) signers;
address[] signersArr;
}
struct Data {
mapping(uint => EntityData) entities;
mapping(bytes32 => uint) entityIds;
uint nEntities;
}
// METHODS
/**
* Creates a new entity
* @param self {object} - The data containing the entity mappings
* @param entitDatayHash {string} - The ipfs multihash address of the entity information in json format
* @param urlHash {bytes32} - The sha256 hash of the URL of the entity
* @param expirationDate {uint} - The expiration date of the current entity
* @param renewalPeriod {uint} - The time period which will be added to the current date or expiration date when a renewal is requested
* @return {uint} The id of the created entity
*/
function create(Data storage self, uint entityId, string entitDatayHash, bytes32 urlHash, uint expirationDate, uint renewalPeriod) isExpirationDateValid(expirationDate) isRenewalPeriodValid(renewalPeriod) public {
self.entities[entityId] = EntityData({
owner: msg.sender,
dataHash: entitDatayHash,
urlHash: urlHash,
status: 1,
expiration: expirationDate,
renewalPeriod: renewalPeriod,
oraclizeQueryId: 0,
signersArr: new address[](0)
});
EntityCreated(entityId);
}
/**
* Process validation after the oraclize callback
* @param self {object} - The data containing the entity mappings
* @param queryId {bytes32} - The id of the oraclize query (returned by the call to oraclize_query method)
* @param result {string} - The result of the query
*/
function processValidation(Data storage self, bytes32 queryId, string result) public {
uint entityId = self.entityIds[queryId];
self.entityIds[queryId] = 0;
EntityData storage entity = self.entities[entityId];
require (queryId == entity.oraclizeQueryId);
string memory entityIdStr = uintToString(entityId);
string memory toCompare = strConcat(entityIdStr, ":", entity.dataHash);
if (stringsEqual(result, toCompare)) {
if (entity.status == 4) { // if entity is waiting for renewal
uint initDate = max(entity.expiration, now);
entity.expiration = initDate + entity.renewalPeriod;
}
entity.status = 2; // set entity status to valid
EntityValidated(entityId);
} else {
entity.status = 1; // set entity status to validation pending
EntityInvalid(entityId);
}
}
/**
* Sets a new expiration date for the entity. It will trigger an entity validation through the oracle, so it must be paid.
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param expirationDate {uint} - The new expiration date of the entity
*/
function setExpiration (Data storage self, uint entityId, uint expirationDate) isNotClosed(self, entityId) onlyEntity(self, entityId) isExpirationDateValid(expirationDate) public {
EntityData storage entity = self.entities[entityId];
entity.status = 1;
entity.expiration = expirationDate;
EntityExpirationSet(entityId);
}
/**
* Sets a new renewal interval
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param renewalPeriod {uint} - The new renewal interval (in seconds)
*/
function setRenewalPeriod (Data storage self, uint entityId, uint renewalPeriod) isNotClosed(self, entityId) onlyEntity(self, entityId) isRenewalPeriodValid(renewalPeriod) public {
EntityData storage entity = self.entities[entityId];
entity.renewalPeriod = renewalPeriod;
EntityRenewalSet(entityId);
}
/**
* Close an entity. This status will not allow further operations on the entity.
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
*/
function closeEntity(Data storage self, uint entityId) isNotClosed(self, entityId) onlyEntity(self, entityId) public {
self.entities[entityId].status = 8;
EntityClosed(entityId);
}
/**
* Registers a new signer in an entity
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param signerAddress {address} - The address of the signer to be registered
* @param signerDataHash {uint} - The IPFS multihash address of signer information in json format
*/
function registerSigner(Data storage self, uint entityId, address signerAddress, string signerDataHash) isValidEntity(self, entityId) onlyEntity(self, entityId) signerIsNotYetRegistered(self, entityId, signerAddress) public {
self.entities[entityId].signersArr.push(signerAddress);
self.entities[entityId].signers[signerAddress] = SignerData({
signerDataHash: signerDataHash,
status: 1
});
SignerAdded(entityId, signerAddress);
}
/**
* Confirms signer registration
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param signerDataHash {string} - The ipfs data hash of the signer to confirm
*/
function confirmSignerRegistration(Data storage self, uint entityId, string signerDataHash) isValidEntity(self, entityId) isWaitingConfirmation(self, entityId, signerDataHash) public {
self.entities[entityId].signers[msg.sender].status = 2;
SignerConfirmed(entityId, msg.sender);
}
/**
* Removes a signer from an entity
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param signerAddress {address} - The address of the signer to be removed
*/
function removeSigner(Data storage self, uint entityId, address signerAddress) isValidEntity(self, entityId) onlyEntity(self, entityId) public {
internalRemoveSigner(self, entityId, signerAddress);
}
/**
* Removes a signer from an entity (internal use, without modifiers)
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param signerAddress {address} - The address of the signer to be removed
*/
function internalRemoveSigner(Data storage self, uint entityId, address signerAddress) private {
EntityData storage entity = self.entities[entityId];
address[] storage signersArr = entity.signersArr;
SignerData storage signer = entity.signers[signerAddress];
if (bytes(signer.signerDataHash).length != 0 || signer.status != 0) {
signer.status = 0;
signer.signerDataHash = '';
delete entity.signers[signerAddress];
// Update array for iterator
uint i = 0;
for (i; signerAddress != signersArr[i]; i++) {}
signersArr[i] = signersArr[signersArr.length - 1];
signersArr[signersArr.length - 1] = 0;
signersArr.length = signersArr.length - 1;
SignerRemoved(entityId, signerAddress);
}
}
/**
* Leave the specified entity (remove signer if found)
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
*/
function leaveEntity(Data storage self, uint entityId) signerBelongsToEntity(self, entityId) public {
internalRemoveSigner(self, entityId, msg.sender);
}
/**
* Checks if an entity can be validated
* @param entityId {uint} - The id of the entity to validate
* @param url {string} - The URL of the entity
* @return {bytes32} - The id of the oraclize query
*/
function canValidateSigningEntity(Data storage self, uint entityId, string url) isNotClosed(self, entityId) isRegisteredURL(self, entityId, url) view public returns (bool) {
return true;
}
/**
* Checks if an entity validity can be renewed
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity to validate
* @param url {string} - The URL of the entity
* @return {bool} - True if renewal is possible
*/
function canRenew(Data storage self, uint entityId, string url) isValidatedEntity(self, entityId) isRenewalPeriod(self, entityId) isRegisteredURL(self, entityId, url) view public returns (bool) {
return true;
}
/**
* Checks if an entity can issue certificate (from its signers)
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity to check
* @return {bool} - True if issuance is possible
*/
function canIssueCertificates(Data storage self, uint entityId) isNotClosed(self, entityId) notExpired(self, entityId) signerBelongsToEntity(self, entityId) view public returns (bool) {
return true;
}
/**
* @dev Updates entity data
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param entityDataHash {string} - The ipfs multihash address of the entity information in json format
* @param urlHash {bytes32} - The sha256 hash of the URL of the entity
*/
function updateEntityData(Data storage self, uint entityId, string entityDataHash, bytes32 urlHash) isNotClosed(self, entityId) onlyEntity(self, entityId) public {
EntityData storage entity = self.entities[entityId];
entity.dataHash = entityDataHash;
entity.urlHash = urlHash;
entity.status = 1;
EntityDataUpdated(entityId);
}
/**
* Update the signer data in the requestes entities
* @param self {object} - The data containing the entity mappings
* @param entityIds {array} - The ids of the entities to update
* @param signerDataHash {string} - The ipfs multihash of the new signer data
*/
function updateSignerData(Data storage self, uint[] entityIds, string signerDataHash) signerBelongsToEntities(self, entityIds) public {
uint[] memory updated = new uint[](entityIds.length);
for (uint i = 0; i < entityIds.length; i++) {
uint entityId = entityIds[i];
SignerData storage signer = self.entities[entityId].signers[msg.sender];
if (signer.status != 2) {
continue;
}
signer.status = 3;
signer.signerDataHash = signerDataHash;
updated[i] = entityId;
}
SignerDataUpdated(updated, msg.sender);
}
/**
* Accepts a new signer data update in the entity
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param signerAddress {address} - The address of the signer update to be accepted
* @param signerDataHash {uint} - The IPFS multihash address of signer information in json format to be accepted
*/
function acceptSignerUpdate(Data storage self, uint entityId, address signerAddress, string signerDataHash) onlyEntity(self, entityId) notExpired(self, entityId) signerUpdateCanBeAccepted(self, entityId, signerAddress, signerDataHash) public {
EntityData storage entity = self.entities[entityId];
entity.signers[signerAddress].status = 2;
SignerUpdateAccepted(entityId, signerAddress);
}
// HELPER METHODS
/**
* Returns the max of two numbers
* @param a {uint} - Input number a
* @param b {uint} - Input number b
* @return {uint} - The maximum of the two inputs
*/
function max(uint a, uint b) pure public returns(uint) {
if (a > b) {
return a;
} else {
return b;
}
}
/**
* @dev Compares two strings
* @param _a {string} - One of the strings
* @param _b {string} - The other string
* @return {bool} True if the two strings are equal, false otherwise
*/
function stringsEqual(string memory _a, string memory _b) pure internal returns (bool) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
if (a.length != b.length)
return false;
for (uint i = 0; i < a.length; i ++) {
if (a[i] != b[i])
return false;
}
return true;
}
function strConcat(string _a, string _b, string _c, string _d, string _e) pure internal returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) {babcde[k++] = _ba[i];}
for (i = 0; i < _bb.length; i++) {babcde[k++] = _bb[i];}
for (i = 0; i < _bc.length; i++) {babcde[k++] = _bc[i];}
for (i = 0; i < _bd.length; i++) {babcde[k++] = _bd[i];}
for (i = 0; i < _be.length; i++) {babcde[k++] = _be[i];}
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) pure internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) pure internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) pure internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// uint to string
function uintToString(uint v) pure public returns (string) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i); // i + 1 is inefficient
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - j - 1]; // to avoid the off-by-one error
}
string memory str = string(s); // memory isn't implicitly convertible to storage
return str;
}
/**
* Set the oraclize query id of the last request
* @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity
* @param queryId {bytes32} - The query id from the oraclize request
*/
function setOraclizeQueryId(Data storage self, uint id, bytes32 queryId) public {
self.entities[id].oraclizeQueryId = queryId;
}
// Helper functions
/**
* Returns True if specified entity is validated or waiting to be renewed. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity to check
* @return {bool} - True if the entity is validated
*/
function isValidated(Data storage self, uint id) view public returns (bool) {
return (id > 0 && (self.entities[id].status == 2 || self.entities[id].status == 4));
}
/**
* Returns True if specified entity is not expired. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity to check
* @return {bool} - True if the entity is not expired
*/
function isExpired(Data storage self, uint id) view public returns (bool) {
return (id > 0 && (self.entities[id].expiration < now));
}
/**
* Returns True if specified entity is closed.
* @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity to check
* @return {bool} - True if the entity is closed
*/
function isClosed(Data storage self, uint id) view public returns (bool) {
return self.entities[id].status == 8;
}
/**
* Returns True if specified entity is validated and not expired
* @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity to check
* @return {bool} - True if the entity is validated
*/
function isValid(Data storage self, uint id) view public returns (bool) {
return isValidated(self, id) && !isExpired(self, id) && !isClosed(self, id);
}
/**
* Returns True if specified entity exists
* @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity to check
* @return {bool} - True if the entity exists
*/
function exists(Data storage self, uint id) view public returns(bool) {
EntityData storage entity = self.entities[id];
return entity.status > 0;
}
// MODIFIERS
/**
* Valid if the renewal period is less than 31 days
* @param renewalPeriod {uint} - The renewal period to check (in seconds)
*/
modifier isRenewalPeriodValid(uint renewalPeriod) {
require(renewalPeriod >= 0 && renewalPeriod <= 32 * 24 * 60 * 60); // Renewal period less than 32 days
_;
}
/**
* Valid if the expiration date is in less than 31 days
* @param expiration {uint} - The expiration date (in seconds)
*/
modifier isExpirationDateValid(uint expiration) {
require(expiration - now > 0 && expiration - now <= 32 * 24 * 60 * 60); // Expiration date is in less than 32 days in the future
_;
}
/**
* Returns True if specified entity is validated or waiting to be renewed. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity to check
*/
modifier isValidatedEntity(Data storage self, uint id) {
require (isValidated(self, id));
_;
}
/**
* Returns True if specified entity is validated or waiting to be renewed, not expired and not closed. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity to check
*/
modifier isValidEntity(Data storage self, uint id) {
require (isValid(self, id));
_;
}
/**
* Returns True if specified entity is validated. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity to check
*/
modifier notExpired(Data storage self, uint id) {
require (!isExpired(self, id));
_;
}
/**
* Returns True if tansaction sent by owner of entity. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity to check
*/
modifier onlyEntity(Data storage self, uint id) {
require (msg.sender == self.entities[id].owner);
_;
}
/**
* Returns True if an URL is the one associated to the entity. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param url {string} - The URL
*/
modifier isRegisteredURL(Data storage self, uint entityId, string url) {
require (self.entities[entityId].urlHash == sha256(url));
_;
}
/**
* Returns True if current time is in renewal period for a valid entity. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity to check
*/
modifier isRenewalPeriod(Data storage self, uint entityId) {
EntityData storage entity = self.entities[entityId];
require (entity.renewalPeriod > 0 && entityId > 0 && (entity.expiration - entity.renewalPeriod < now) && entity.status == 2);
_;
}
/**
* True if sender is registered in entity. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
*/
modifier signerBelongsToEntity(Data storage self, uint entityId) {
EntityData storage entity = self.entities[entityId];
require (entityId > 0 && (bytes(entity.signers[msg.sender].signerDataHash).length != 0) && (entity.signers[msg.sender].status == 2));
_;
}
/**
* True if sender is registered in all the entities. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param entityIds {array} - The ids of the entities
*/
modifier signerBelongsToEntities(Data storage self, uint[] entityIds) {
for (uint i = 0; i < entityIds.length; i++) {
uint entityId = entityIds[i];
EntityData storage entity = self.entities[entityId];
require (entityId > 0 && (entity.signers[msg.sender].status != 0));
}
_;
}
/**
* True if the signer was not yet added to an entity.
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param signerAddress {address} - The signer to check
*/
modifier signerIsNotYetRegistered(Data storage self, uint entityId, address signerAddress) {
EntityData storage entity = self.entities[entityId];
require (entity.signers[signerAddress].status == 0);
_;
}
/**
* True if the entity is validated AND the signer has a pending update with a matching IPFS data hash
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
* @param signerAddress {address} - The signer to check
* @param signerDataHash {string} - The signer IPFS data pending of confirmation
*/
modifier signerUpdateCanBeAccepted(Data storage self, uint entityId, address signerAddress, string signerDataHash) {
require (isValid(self, entityId));
EntityData storage entity = self.entities[entityId];
string memory oldSignerDatHash = entity.signers[signerAddress].signerDataHash;
require (entity.signers[signerAddress].status == 3 && stringsEqual(oldSignerDatHash, signerDataHash));
_;
}
/**
* True if the sender is registered as a signer in entityId and the status is VALIDATION_PENDING. False otherwise.
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity to check
*/
modifier isWaitingConfirmation(Data storage self, uint entityId, string signerDataHash) {
EntityData storage entity = self.entities[entityId];
SignerData storage signer = entity.signers[msg.sender];
require ((bytes(signer.signerDataHash).length != 0) && (signer.status == 1) && stringsEqual(signer.signerDataHash, signerDataHash));
_;
}
/**
* True if the entity has not been closed
* @param self {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity to check
*/
modifier isNotClosed(Data storage self, uint entityId) {
require(!isClosed(self, entityId));
_;
}
// EVENTS
event EntityCreated(uint indexed entityId);
event EntityValidated(uint indexed entityId);
event EntityDataUpdated(uint indexed entityId);
event EntityInvalid(uint indexed entityId);
event SignerAdded(uint indexed entityId, address indexed signerAddress);
event SignerDataUpdated(uint[] entities, address indexed signerAddress);
event SignerUpdateAccepted(uint indexed entityId, address indexed signerAddress);
event SignerRemoved(uint indexed entityId, address signerAddress);
event EntityClosed(uint indexed entityId);
event SignerConfirmed(uint indexed entityId, address signerAddress);
event EntityExpirationSet(uint indexed entityId);
event EntityRenewalSet(uint indexed entityId);
}
library SignLib {
// METHODS
/**
* Requests the signature for a certificate to an entity.
* Only one request possible (future ones are renewals)
* @param ed {object} - The data containing the entity mappings
* @param cd {object} - The data containing the certificate mappings
* @param certificateId {uint} - The id of the certificate
* @param entityId {uint} - The id of the entity
*/
function requestSignatureToEntity(EntityLib.Data storage ed, CertsLib.Data storage cd, uint certificateId, uint entityId) canRequestSignature(ed, cd, certificateId) isValid(ed, entityId) notHasSigningRequest(cd, certificateId, entityId) public {
CertsLib.CertData storage certificate = cd.certificates[certificateId];
addMissingSignature(certificate, entityId, 0x1, 0);
EntitySignatureRequested(certificateId, entityId);
}
/**
* Requests the signature for a certificate to a peer
* Only one request possible (future ones are renewals)
* @param cd {object} - The data containing the certificate mappings
* @param certificateId {uint} - The id of the certificate
* @param peer {address} - The address of the peer
*/
function requestSignatureToPeer(EntityLib.Data storage ed, CertsLib.Data storage cd, uint certificateId, address peer) canRequestSignature(ed, cd, certificateId) notHasPeerSignature(cd, certificateId, peer) public {
CertsLib.CertData storage certificate = cd.certificates[certificateId];
addMissingPeerSignature(certificate, peer, 0x1, 0);
PeerSignatureRequested(certificateId, peer);
}
/**
* Entity signs a certificate with pending request
* @param ed {object} - The data containing the entity mappings
* @param cd {object} - The data containing the certificate mappings
* @param entityId {uint} - The id of the entity
* @param certificateId {uint} - The id of the certificate
* @param expiration {uint} - The expiration time of the signature (in seconds)
* @param _purpose {bytes32} - The sha-256 hash of the purpose data
*/
function signCertificateAsEntity(EntityLib.Data storage ed, CertsLib.Data storage cd, uint entityId, uint certificateId, uint expiration, bytes32 _purpose) isValid(ed, entityId) signerBelongsToEntity(ed, entityId) hasPendingSignatureOrIsOwner(ed, cd, certificateId, entityId) public {
CertsLib.CertData storage certificate = cd.certificates[certificateId];
bytes32 purpose = (_purpose == 0x0 || _purpose == 0x1) ? bytes32(0x2) : _purpose;
addMissingSignature(certificate, entityId, purpose, expiration);
CertificateSignedByEntity(certificateId, entityId, msg.sender);
}
/**
* Peer signs a certificate with pending request
* @param cd {object} - The data containing the certificate mappings
* @param certificateId {uint} - The id of the certificate
* @param expiration {uint} - The expiration time of the signature (in seconds)
* @param _purpose {bytes32} - The sha-256 hash of the purpose data
*/
function signCertificateAsPeer(CertsLib.Data storage cd, uint certificateId, uint expiration, bytes32 _purpose) hasPendingPeerSignatureOrIsOwner(cd, certificateId) public {
CertsLib.CertData storage certificate = cd.certificates[certificateId];
bytes32 purpose = (_purpose == 0x0 || _purpose == 0x1) ? bytes32(0x2) : _purpose;
addMissingPeerSignature(certificate, msg.sender, purpose, expiration);
CertificateSignedByPeer(certificateId, msg.sender);
}
// HELPER FUNCTIONS
/**
* Add an entity signature to the entity signatures array (if missing) and set the specified status and expiration
* @param certificate {object} - The certificate to add the peer signature
* @param entityId {uint} - The id of the entity signing the certificate
* @param status {uint} - The status/purpose of the signature
* @param expiration {uint} - The expiration time of the signature (in seconds)
*/
function addMissingSignature(CertsLib.CertData storage certificate, uint entityId, bytes32 status, uint expiration) private {
uint[] storage entitiesArr = certificate.entitiesArr;
for (uint i = 0; i < entitiesArr.length && entitiesArr[i] != entityId; i++) {}
if (i == entitiesArr.length) {
entitiesArr.push(entityId);
}
certificate.entities[entityId].status = status;
certificate.entities[entityId].exp = expiration;
}
/**
* Add a peer signature to the signatures array (if missing) and set the specified status and expiration
* @param certificate {object} - The certificate to add the peer signature
* @param peer {address} - The address of the peer to add signature
* @param status {uint} - The status/purpose of the signature
* @param expiration {uint} - The expiration time of the signature (in seconds)
*/
function addMissingPeerSignature(CertsLib.CertData storage certificate, address peer, bytes32 status, uint expiration) private {
address[] storage signaturesArr = certificate.signaturesArr;
for (uint i = 0; i < signaturesArr.length && signaturesArr[i] != peer; i++) {}
if (i == signaturesArr.length) {
signaturesArr.push(peer);
}
certificate.signatures[peer].status = status;
certificate.signatures[peer].exp = expiration;
}
// MODIFIERS
/**
* Returns True if msg.sender is the owner of the specified certificate or the sender is a confirmed signer of certificate entity. False otherwise.
* @param cd {object} - The data containing the certificate mappings
* @param id {uint} - The id of the certificate
*/
modifier canRequestSignature(EntityLib.Data storage ed, CertsLib.Data storage cd, uint id) {
require (cd.certificates[id].owner == msg.sender ||
(cd.certificates[id].entityId > 0 && EntityLib.isValid(ed, cd.certificates[id].entityId) && ed.entities[cd.certificates[id].entityId].signers[msg.sender].status == 0x2)
);
_;
}
/**
* Returns True if specified entity is validated or waiting to be renewed, not expired and not closed. False otherwise.
* @param ed {object} - The data containing the entity mappings
* @param id {uint} - The id of the entity to check
*/
modifier isValid(EntityLib.Data storage ed, uint id) {
require (EntityLib.isValid(ed, id));
_;
}
/**
* Returns True if specified certificate has not been validated yet by entity. False otherwise.
* @param cd {object} - The data containing the certificate mappings
* @param certificateId {uint} - The id of the certificate to check
* @param entityId {uint} - The id of the entity to check
*/
modifier notHasSigningRequest(CertsLib.Data storage cd, uint certificateId, uint entityId) {
require (cd.certificates[certificateId].entities[entityId].status != 0x1);
_;
}
/**
* Returns True if specified certificate has not been signed yet. False otherwise;
* @param cd {object} - The data containing the certificate mappings
* @param certificateId {uint} - The id of the certificate to check
* @param signerAddress {address} - The id of the certificate to check
*/
modifier notHasPeerSignature(CertsLib.Data storage cd, uint certificateId, address signerAddress) {
require (cd.certificates[certificateId].signatures[signerAddress].status != 0x1);
_;
}
/**
* True if sender address is the owner of the entity or is a signer registered in entity. False otherwise.
* @param ed {object} - The data containing the entity mappings
* @param entityId {uint} - The id of the entity
*/
modifier signerBelongsToEntity(EntityLib.Data storage ed, uint entityId) {
require (entityId > 0 && (bytes(ed.entities[entityId].signers[msg.sender].signerDataHash).length != 0) && (ed.entities[entityId].signers[msg.sender].status == 0x2));
_;
}
/**
* True if a signature request has been sent to entity or the issuer of the certificate is requested entity itself. False otherwise.
* @param cd {object} - The data containing the certificate mappings
* @param certificateId {uint} - The id of the certificate to check
* @param entityId {uint} - The id of the entity to check
*/
modifier hasPendingSignatureOrIsOwner(EntityLib.Data storage ed, CertsLib.Data storage cd, uint certificateId, uint entityId) {
require (cd.certificates[certificateId].entities[entityId].status == 0x1 || cd.certificates[certificateId].entityId == entityId);
_;
}
/**
* True if a signature is pending for the sender or the sender is the owner. False otherwise.
* @param cd {object} - The data containing the certificate mappings
* @param certificateId {uint} - The id of the certificate to check
*/
modifier hasPendingPeerSignatureOrIsOwner(CertsLib.Data storage cd, uint certificateId) {
require (cd.certificates[certificateId].signatures[msg.sender].status == 0x1 || cd.certificates[certificateId].owner == msg.sender);
_;
}
// EVENTS
event EntitySignatureRequested(uint indexed certificateId, uint indexed entityId);
event PeerSignatureRequested(uint indexed certificateId, address indexed signerAddress);
event CertificateSignedByEntity(uint indexed certificateId, uint indexed entityId, address indexed signerAddress);
event CertificateSignedByPeer(uint indexed certificateId, address indexed signerAddress);
}
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint capacity) internal constant {
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(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private constant {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private constant returns(uint) {
if(a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Reverts 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 append(buffer memory buf, bytes data) internal constant returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Reverts 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 append(buffer memory buf, uint8 data) internal constant {
if(buf.buf.length + 1 > 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 + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Reverts if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal constant returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.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_CONTENT_FREE = 7;
function shl8(uint8 x, uint8 y) private constant returns (uint8) {
return x * (2 ** y);
}
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private constant {
if(value <= 23) {
buf.append(uint8(shl8(major, 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8(shl8(major, 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8(shl8(major, 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8(shl8(major, 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8(shl8(major, 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private constant {
buf.append(uint8(shl8(major, 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal constant {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal constant {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal constant {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal constant {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal constant returns (bytes) {
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal constant returns (bytes) {
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
// the following variables can be relaxed
// check relaxed random contract under ethereum-examples repo
// for an idea on how to override and replace comit hash vars
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1; //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
if (prefix.length != n_random_bytes) throw;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
contract Ethertify is usingOraclize {
EntityLib.Data ed;
CertsLib.Data cd;
/**
* Creates a contract
*/
function Ethertify() public {
ed.nEntities = 0;
cd.nCerts = 0;
}
// MODIFIERS
/**
* True if the method is executed by oraclize. False otherwise.
*/
modifier isOraclize() {
require (msg.sender == oraclize_cbAddress());
_;
}
// ENTITY METHODS
/**
* Creates a new entity
* @param entityHash {string} - The ipfs multihash address of the entity information in json format
* @param urlHash {bytes32} - The sha256 hash of the URL of the entityç
* @param expirationDate {uint} - The expiration date of the current entity
* @param renewalPeriod {uint} - The time period which will be added to the current date or expiration date when a renewal is requested
* @return {uint} The id of the created entity
*/
function createSigningEntity(string entityHash, bytes32 urlHash, uint expirationDate, uint renewalPeriod) public returns (uint) {
uint entityId = ++ed.nEntities;
EntityLib.create(ed, entityId, entityHash, urlHash, expirationDate, renewalPeriod);
return entityId;
}
/**
* Sets a new expiration date for the entity. It will trigger an entity validation through the oracle, so it must be paid
* @param entityId {uint} - The id of the entity
* @param expirationDate {uint} - The new expiration date of the entity
* @param url {string} - The URL of the entity (for validation through the oracle)
* @param oraclizeGas {uint} - The maximum gas to use during the oraclize callback execution. Will default to 90000 if not provided.
* @param oraclizeGasPrice {uint} - The gas price to use during the oraclize callback invocation.
* @return {bytes32} - The id of the oraclize query
*/
function setExpiration(uint entityId, uint expirationDate, string url, uint oraclizeGas, uint oraclizeGasPrice) public payable returns (bytes32) {
EntityLib.setExpiration(ed, entityId, expirationDate);
return validateSigningEntity(entityId, url, oraclizeGas, oraclizeGasPrice);
}
/**
* Sets a new renewal interval
* @param entityId {uint} - The id of the entity
* @param renewalPeriod {uint} - The new renewal interval (in seconds)
*/
function setRenewalPeriod (uint entityId, uint renewalPeriod) public {
EntityLib.setRenewalPeriod(ed, entityId, renewalPeriod);
}
/**
* Requests the validation of a signing entity
* @param entityId {uint} - The id of the entity to validate
* @param url {string} - The URL of the entity
* @param oraclizeGas {uint} - The maximum gas to use during the oraclize callback execution. Will default to 90000 if not provided.
* @param oraclizeGasPrice {uint} - The gas price to use during the oraclize callback invocation.
* @return {bytes32} - The id of the oraclize query
*/
function validateSigningEntity(uint entityId, string url, uint oraclizeGas, uint oraclizeGasPrice) public payable returns (bytes32) {
uint maxGas = oraclizeGas == 0 ? 88000 : oraclizeGas; // 67000 gas from the process validation callback + 21000 for the transfer
if (EntityLib.canValidateSigningEntity(ed, entityId, url)) {
oraclize_setCustomGasPrice(oraclizeGasPrice);
uint queryCost = oraclize_getPrice("URL", maxGas);
if (queryCost > msg.value) {
OraclizeNotEnoughFunds(entityId, queryCost);
return 0;
}
string memory query = strConcat("html(", url, ").xpath(/html/head/meta[@name='ethertify-entity']/@content)");
bytes32 queryId = oraclize_query("URL", query, maxGas);
ed.entityIds[queryId] = entityId;
EntityLib.setOraclizeQueryId(ed, entityId, queryId);
return queryId;
}
}
/**
* Updates entity data
* @param entityId {uint} - The id of the entity
* @param entityHash {string} - The ipfs multihash address of the entity information in json format
* @param urlHash {bytes32} - The sha256 hash of the URL of the entity
* @param oraclizeGas {uint} - The maximum gas to use during the oraclize callback execution. Will default to 90000 if not provided.
* @param oraclizeGasPrice {uint} - The gas price to use during the oraclize callback invocation.
* @param url {string} - The url used during the validation (after setting the data)
*/
function updateEntityData(uint entityId, string entityHash, bytes32 urlHash, string url, uint oraclizeGas, uint oraclizeGasPrice) public payable {
EntityLib.updateEntityData(ed, entityId, entityHash, urlHash);
validateSigningEntity(entityId, url, oraclizeGas, oraclizeGasPrice);
}
/**
* Update the signer data in the requestes entities
* @param entityIds {array} - The ids of the entities to update
* @param signerDataHash {string} - The ipfs multihash of the new signer data
*/
function updateSignerData(uint[] entityIds, string signerDataHash) public {
EntityLib.updateSignerData(ed, entityIds, signerDataHash);
}
/**
* Accepts a new signer data update in the entity
* @param entityId {uint} - The id of the entity
* @param signerAddress {address} - The address of the signer update to be accepted
* @param signerDataHash {uint} - The IPFS multihash address of signer information in json format to be accepted
*/
function acceptSignerUpdate(uint entityId, address signerAddress, string signerDataHash) public {
EntityLib.acceptSignerUpdate(ed, entityId, signerAddress, signerDataHash);
}
/**
* Requests the renewal of a signing entity
* @param entityId {uint} - The id of the entity to validate
* @param url {string} - The URL of the entity
* @param oraclizeGas {uint} - The maximum gas to use during the oraclize callback execution. Will default to 90000 if not provided.
* @param oraclizeGasPrice {uint} - The gas price to use during the oraclize callback invocation.
* @return {bytes32} - The id of the oraclize query
*/
function requestRenewal(uint entityId, string url, uint oraclizeGas, uint oraclizeGasPrice) public payable returns (bytes32) {
if (EntityLib.canRenew(ed, entityId, url)) {
ed.entities[entityId].status = 4;
return validateSigningEntity(entityId, url, oraclizeGas, oraclizeGasPrice);
}
}
/**
* Close an entity. This status will not allow further operations on the entity.
* @param entityId {uint} - The id of the entity
*/
function closeEntity(uint entityId) public {
EntityLib.closeEntity(ed, entityId);
}
/**
* Executes automatically when oraclize query is finished
* @param queryId {bytes32} - The id of the oraclize query (returned by the call to oraclize_query method)
* @param result {string} - The result of the query
*/
function __callback(bytes32 queryId, string result) isOraclize() public {
EntityLib.processValidation(ed, queryId, result);
}
/**
* Registers a new signer in an entity
* @param entityId {uint} - The id of the entity
* @param signerAddress {address} - The address of the signer to be registered
* @param signerDataHash {uint} - The IPFS multihash address of signer information in json format
*/
function registerSigner(uint entityId, address signerAddress, string signerDataHash) public {
EntityLib.registerSigner(ed, entityId, signerAddress, signerDataHash);
}
/**
* Removes a signer from an entity
* @param entityId {uint} - The id of the entity
* @param signerAddress {address} - The address of the signer to be removed
*/
function removeSigner(uint entityId, address signerAddress) public {
EntityLib.removeSigner(ed, entityId, signerAddress);
}
/**
* Leave the specified entity (remove signer if found)
* @param entityId {uint} - The id of the entity
*/
function leaveEntity(uint entityId) public {
EntityLib.leaveEntity(ed, entityId);
}
/**
* Confirms signer registration
* @param entityId {uint} - The id of the entity
* @param signerDataHash {string} - The ipfs data hash of the signer to confirm
*/
function confirmSignerRegistration(uint entityId, string signerDataHash) public {
EntityLib.confirmSignerRegistration(ed, entityId, signerDataHash);
}
// CERTIFICATE METHODS
/**
* Creates a new POE certificate
* @param dataHash {bytes32} - The hash of the certified data
* @param certHash {bytes32} - The sha256 hash of the json certificate
* @param ipfsDataHash {string} - The ipfs multihash address of the data (0x00 means unkwon)
* @param ipfsCertHash {string} - The ipfs multihash address of the certificate in json format (0x00 means unkwon)
* @return The id of the created certificate
*/
function createPOECertificate(bytes32 dataHash, bytes32 certHash, string ipfsDataHash, string ipfsCertHash) public returns (uint) {
return CertsLib.createPOECertificate(cd, dataHash, certHash, ipfsDataHash, ipfsCertHash);
}
/**
* Creates a new certificate (with known owner)
* @param dataHash {bytes32} - The hash of the certified data
* @param certHash {bytes32} - The sha256 hash of the json certificate
* @param ipfsDataHash {string} - The ipfs multihash address of the data (0x00 means unkwon)
* @param ipfsCertHash {string} - The ipfs multihash address of the certificate in json format (0x00 means unkwon)
* @param entityId {uint} - The entity id which issues the certificate (0 if not issued by an entity)
* @return {uint} The id of the created certificate
*/
function createCertificate(bytes32 dataHash, bytes32 certHash, string ipfsDataHash, string ipfsCertHash, uint entityId) public returns (uint) {
return CertsLib.createCertificate(cd, ed, dataHash, certHash, ipfsDataHash, ipfsCertHash, entityId);
}
/**
* Request transfering the ownership of a certificate.
* The owner can be a peer or an entity (never both), so only one of newOwner or newEntity must be different than 0.
* If the specified certificateId belongs to an entity, the msg.sender must be a valid signer for the entity. Otherwise the msg.sender must be the current owner.
* @param certificateId {uint} - The id of the certificate to transfer
* @param newOwner {address} - The address of the new owner
*/
function requestCertificateTransferToPeer(uint certificateId, address newOwner) public {
return CertsLib.requestCertificateTransferToPeer(cd, ed, certificateId, newOwner);
}
/**
* Request transfering the ownership of a certificate.
* The owner can be a peer or an entity (never both), so only one of newOwner or newEntity must be different than 0.
* If the specified certificateId belongs to an entity, the msg.sender must be a valid signer for the entity. Otherwise the msg.sender must be the current owner.
* @param certificateId {uint} - The id of the certificate to transfer
* @param newEntityId {uint} - The id of the new entity
*/
function requestCertificateTransferToEntity(uint certificateId, uint newEntityId) public {
return CertsLib.requestCertificateTransferToEntity(cd, ed, certificateId, newEntityId);
}
/**
* Accept the certificate transfer
* @param certificateId {uint} - The id of the certificate to transfer
*/
function acceptCertificateTransfer(uint certificateId) public {
return CertsLib.acceptCertificateTransfer(cd, ed, certificateId);
}
/**
* Cancel the certificate transfer
* @param certificateId {uint} - The id of the certificate to transfer
*/
function cancelCertificateTransfer(uint certificateId) public {
return CertsLib.cancelCertificateTransfer(cd, ed, certificateId);
}
/**
* Updates ipfs multihashes of a particular certificate
* @param certId {uint} - The id of the certificate
* @param ipfsDataHash {string} - The ipfs multihash address of the data (0x00 means unkwon)
* @param ipfsCertHash {string} - The ipfs multihash address of the certificate in json format (0x00 means unkwon)
*/
function setIPFSData(uint certId, string ipfsDataHash, string ipfsCertHash) public {
CertsLib.setIPFSData(cd, certId, ipfsDataHash, ipfsCertHash);
}
// SIGNATURE METHODS
/**
* Requests the signature for a certificate to an entity
* @param certificateId {uint} - The id of the certificate
* @param entityId {uint} - The id of the entity
*/
function requestSignatureToEntity(uint certificateId, uint entityId) public {
SignLib.requestSignatureToEntity(ed, cd, certificateId, entityId);
}
/**
* Requests the signature for a certificate to a peer
* @param certificateId {uint} - The id of the certificate
* @param peer {address} - The address of the peer
*/
function requestSignatureToPeer(uint certificateId, address peer) public {
SignLib.requestSignatureToPeer(ed, cd, certificateId, peer);
}
/**
* Entity signs a certificate with pending request
* @param entityId {uint} - The id of the entity
* @param certificateId {uint} - The id of the certificate
* @param expiration {uint} - The expiration time of the signature (in seconds)
* @param purpose {bytes32} - The sha-256 hash of the purpose data
*/
function signCertificateAsEntity(uint entityId, uint certificateId, uint expiration, bytes32 purpose) public {
SignLib.signCertificateAsEntity(ed, cd, entityId, certificateId, expiration, purpose);
}
/**
* Peer signs a certificate with pending request
* @param certificateId {uint} - The id of the certificate
* @param expiration {uint} - The expiration time of the signature (in seconds)
* @param purpose {bytes32} - The sha-256 hash of the purpose data
*/
function signCertificateAsPeer(uint certificateId, uint expiration, bytes32 purpose) public {
SignLib.signCertificateAsPeer(cd, certificateId, expiration, purpose);
}
// CUSTOM GETTERS
/**
* Get default info from internal contract
*/
function internalState() constant public returns (uint numEntities, uint numCertificates) {
return (
ed.nEntities,
cd.nCerts
);
}
/**
* Gets the entity data by id
* @param entityId {uint} - The id of the entity
* @return {object} The data of a signing entity
*/
function getSigningEntityInfo(uint entityId) constant public returns (address owner, string dataHash, uint status, bytes32 urlHash, uint expiration, uint renewalPeriod, uint numSigners) {
return (
ed.entities[entityId].owner,
ed.entities[entityId].dataHash,
ed.entities[entityId].status,
ed.entities[entityId].urlHash,
ed.entities[entityId].expiration,
ed.entities[entityId].renewalPeriod,
ed.entities[entityId].signersArr.length
);
}
/**
* Get the last oraclize query Id of the specified entity
* @param entityId {uint} - The id of the entity
* @return {bytes32} The last oraclize query id of the entity
*/
function getOraclizeQuery(uint entityId) constant public returns (bytes32 oraclizeQueryId) {
return ed.entities[entityId].oraclizeQueryId;
}
/**
* Gets the signers data from an entity (by address or index)
* @param entityId {uint} - The id of the entity
* @param signerAddress {address} - The address of the signer (if known)
* @param index {uint} - The index of the signer
* @return {object} The signer details
*/
function getSignerData(uint entityId, address signerAddress, uint index) constant public returns (address signer, uint status, string ipfsMultiHash) {
uint s = 0;
string memory h = "";
if (signerAddress != 0) {
s = ed.entities[entityId].signers[signerAddress].status;
h = ed.entities[entityId].signers[signerAddress].signerDataHash;
} else if (signerAddress == 0 && index < ed.entities[entityId].signersArr.length) {
signerAddress = ed.entities[entityId].signersArr[index];
s = ed.entities[entityId].signers[signerAddress].status;
h = ed.entities[entityId].signers[signerAddress].signerDataHash;
}
return (signerAddress, s, h);
}
/**
* Gets the certificate data by id
* @param certificateId {uint} - The id of the certificate
* @return {object} The data of a certificate
*/
function getCertificateInfo(uint certificateId) constant public returns (address owner, uint entityId, bytes32 certHash, string ipfsCertHash, bytes32 dataHash, string ipfsDataHash, uint numEntitySignatures, uint numPeerSignatures, address newOwnerTransferRequest, uint newEntityTransferRequest) {
CertsLib.CertData storage cert = cd.certificates[certificateId];
CertsLib.TransferData storage req = cd.transferRequests[certificateId];
return (
cert.owner,
cert.entityId,
cert.certHash,
cert.ipfsCertHash,
cert.dataHash,
cert.ipfsDataHash,
cert.entitiesArr.length,
cert.signaturesArr.length,
req.newOwner,
req.newEntityId
);
}
/**
* Gets the entity signature info from a certificate and signing entity
* @param certificateId {uint} - The id of the certificate
* @param entityId {uint} - The id of the entity
* @param entityIndex {uint} - The index of the entity in the array
* @return {uint, uint} The status/purpose and expiration date
*/
function getEntitySignatureInfoFromCertificate(uint certificateId, uint entityId, uint entityIndex) constant public returns (uint id, bytes32 status, uint expiration) {
bytes32 s = 0x0;
uint e = 0;
if (entityId != 0 ) {
s = cd.certificates[certificateId].entities[entityId].status;
e = cd.certificates[certificateId].entities[entityId].exp;
} else if (entityId == 0) {
entityId = cd.certificates[certificateId].entitiesArr[entityIndex];
s = cd.certificates[certificateId].entities[entityId].status;
e = cd.certificates[certificateId].entities[entityId].exp;
} else {
entityId = 0;
}
return (entityId, s, e);
}
/**
* Gets the peer signature info from a certificate and signing entity
* @param certificateId {uint} - The id of the certificate
* @param peerAddress {address} - If the address is supplied the info is retrieved from the peer
* @param peerIndex {uint} - The index of the peer to retrieve data from
* @return {uint, uint} The status/purpose and expiration date
*/
function getPeerSignatureInfoFromCertificate(uint certificateId, address peerAddress, uint peerIndex) constant public returns (address addr, bytes32 status, uint expiration) {
bytes32 s = 0x0;
uint e = 0;
if (peerAddress != 0) {
s = cd.certificates[certificateId].signatures[peerAddress].status;
e = cd.certificates[certificateId].signatures[peerAddress].exp;
} else if (peerAddress == 0) {
peerAddress = cd.certificates[certificateId].signaturesArr[peerIndex];
s = cd.certificates[certificateId].signatures[peerAddress].status;
e = cd.certificates[certificateId].signatures[peerAddress].exp;
}
return (peerAddress, s, e);
}
// EVENTS
event EntityCreated(uint indexed entityId);
event EntityValidated(uint indexed entityId);
event EntityDataUpdated(uint indexed entityId);
event EntityInvalid(uint indexed entityId);
event SignerAdded(uint indexed entityId, address indexed signerAddress);
event SignerDataUpdated(uint[] entities, address indexed signerAddress);
event SignerUpdateAccepted(uint indexed entityId, address indexed signerAddress);
event SignerRemoved(uint indexed entityId, address signerAddress);
event EntityClosed(uint indexed entityId);
event SignerConfirmed(uint indexed entityId, address signerAddress);
event EntityExpirationSet(uint indexed entityId);
event EntityRenewalSet(uint indexed entityId);
event POECertificate(uint indexed certificateId);
event Certificate(uint indexed certificateId);
event CertificateTransferRequestedToPeer(uint indexed certificateId, address newOwner);
event CertificateTransferRequestedToEntity(uint indexed certificateId, uint newEntityId);
event CertificateTransferAccepted(uint indexed certificateId, address newOwner, uint newEntityId);
event CertificateTransferCancelled(uint indexed certificateId);
event EntitySignatureRequested(uint indexed certificateId, uint indexed entityId);
event PeerSignatureRequested(uint indexed certificateId, address indexed signerAddress);
event CertificateSignedByEntity(uint indexed certificateId, uint indexed entityId, address indexed signerAddress);
event CertificateSignedByPeer(uint indexed certificateId, address indexed signerAddress);
event OraclizeNotEnoughFunds(uint indexed entityId, uint queryCost);
}
|
Creates a new POE certificate self {object} - The data containing the certificate mappings dataHash {bytes32} - The hash of the certified data certHash {bytes32} - The sha256 hash of the json certificate ipfsDataHash {string} - The ipfs multihash address of the data (0x00 means unkwon) ipfsCertHash {string} - The ipfs multihash address of the certificate in json format (0x00 means unkwon) return The id of the created certificate/
|
function createPOECertificate(Data storage self, bytes32 dataHash, bytes32 certHash, string ipfsDataHash, string ipfsCertHash) public returns (uint) {
require (hasData(dataHash, certHash, ipfsDataHash, ipfsCertHash));
uint certId = ++self.nCerts;
self.certificates[certId] = CertData({
owner: 0,
entityId: 0,
certHash: certHash,
ipfsCertHash: ipfsCertHash,
dataHash: dataHash,
ipfsDataHash: ipfsDataHash,
entitiesArr: new uint[](0),
signaturesArr: new address[](0)
});
POECertificate(certId);
return certId;
}
| 1,068,191
|
./partial_match/1/0x2fDc7b6d7Df9e8d600F96441C35ef75F640DcC83/sources/PotPool.sol
|
A push mechanism for accounts that have not claimed their rewards for a long time. The implementation is semantically analogous to getReward(), but uses a push pattern instead of pull pattern. If it is a normal user and not smart contract, then the requirement will pass If it is a smart contract, then make sure that it is not on our greyList.
|
function pushAllRewards(address recipient) public updateRewards(recipient) onlyGovernance {
bool rewardPayout = !(smartContractStakers[recipient] && greyListEnabled && IController(controller()).greyList(recipient));
for(uint256 i = 0 ; i < rewardTokens.length; i++ ){
uint256 reward = earned(rewardTokens[i], recipient);
if (reward > 0) {
rewardsForToken[rewardTokens[i]][recipient] = 0;
if (rewardPayout) {
IERC20(rewardTokens[i]).safeTransfer(recipient, reward);
emit RewardPaid(recipient, rewardTokens[i], reward);
emit RewardDenied(recipient, rewardTokens[i], reward);
}
}
}
}
| 2,713,382
|
pragma solidity >=0.6.0 <0.8.0;
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./ICakeClub.sol";
interface CakeVault{
function cake() external view returns (address);
function enterStaking(uint256 amount) external;
function leaveStaking(uint256 amount) external;
function pendingCake(uint256 _pid, address _user) external view returns (uint256);
function userInfo(uint256 _pid, address _user) external view returns (uint256, uint256);
function emergencyWithdraw(uint256 _pid) external;
}
interface IPrestigeClub{
function depositSum() external view returns (uint128);
function totalDownlineVolume() external view returns (uint128);
}
contract CakeClub is Ownable(){ //, ICakeClub
using SafeMath for uint256;
IERC20 public cake;
CakeVault vault;
IPrestigeClub prestigeclub;
constructor(address _vault, address _syrup) public {
vault = CakeVault(_vault);
cake = IERC20(vault.cake());
cake.approve(_vault, ~uint256(0));
IERC20(_syrup).approve(_vault, ~uint256(0));
}
uint256 public alreadyWithdrawn;
uint256 public depositedCake;
uint256 public estimatedPeth;
uint256 public rewardLastEstimation;
uint256 constant payout_interval = 1 days;
uint256 last_payout_calculation = block.timestamp - (block.timestamp % payout_interval);
uint256 dust = 100000;
uint256 constant ownerShares = 15;
uint256 public ownerProvision;
event Withdrawal(address indexed addr, uint256 peth, uint256 cake);
uint256 baseRate = 800 + //Interest
250 + //Directs
390; //Pool (65 * 6)
function getDailyRate() public view returns (uint256) {
//1e12 here because 1e18 is 100% -> prestigeclub percentages are ppm -> *1e12
//And 2 seperate 1e12 * x because downlineRate shoudl be as exact as possible without truncations
uint256 downlineRate = uint256(1e12).mul(uint256(prestigeclub.totalDownlineVolume()).mul(25)).div(uint256(prestigeclub.depositSum()));
return
uint256((baseRate) * 1e12)
.add(downlineRate);
}
/**
Withdraws pending Cake Rewards
@return Returns amount of withdrawn Rewards
*/
function _withdrawRewards() internal returns (uint256) {
uint256 balance = cake.balanceOf(address(this));
vault.leaveStaking(0);
uint256 diff = cake.balanceOf(address(this)).sub(balance);
alreadyWithdrawn = alreadyWithdrawn.add(diff);
return diff;
}
function invest() public onlyPrestige {
uint256 balance = cake.balanceOf(address(this));
uint256 rewards = _withdrawRewards();
//Invest into Masterchef
vault.enterStaking(balance + rewards);
depositedCake += balance;
}
function totalProfit() public view returns (uint256) {
return vault.pendingCake(0, address(this)).add(alreadyWithdrawn);
}
//Note This function is only used by the frontend
function outputWithEstimation(uint256 peth) public view returns (uint256){
uint pethEstimation = estimatedPeth;
uint rewards = rewardLastEstimation;
uint dayz = (block.timestamp.sub(last_payout_calculation)) / payout_interval; //payout_interval will never be 0
if(dayz > 0){
pethEstimation = pethEstimation.add(uint256(prestigeclub.depositSum()).mul(getDailyRate()).mul(dayz).div(1e18));
rewards = totalProfit();
}
return 1 ether * peth / pethEstimation * rewards / 1 ether;
}
function output(uint256 peth) public view returns (uint256) {
return uint256(1 ether).mul(peth).div(estimatedPeth).mul(rewardLastEstimation) / 1 ether;
}
function withdraw(uint256 peth, address to) public onlyPrestige {
updateEstimation();
uint256 cakeAmount = output(peth);
uint256 pending = vault.pendingCake(0, address(this));
// uint256 pending = pendingTotal * 85 / 100;
uint256 withdrawAmount = 0;
if(pending < cakeAmount){ //Since compounding will occur, withdrawal of Stake is possible
withdrawAmount = cakeAmount.sub(pending);
}
vault.leaveStaking(withdrawAmount);
alreadyWithdrawn = alreadyWithdrawn.add(pending);
uint256 ownerSharesC = cakeAmount * ownerShares / 100; //ownerShares can´t be in the range of overflows
ownerProvision += ownerSharesC;
cake.transfer(to, cakeAmount.sub(ownerSharesC));
uint256 balanceLeft = cake.balanceOf(address(this));
if(balanceLeft > 0){
vault.enterStaking(balanceLeft);
}
emit Withdrawal(to, peth, cakeAmount);
(uint256 deposit, ) = vault.userInfo(0, address(this));
require(deposit >= depositedCake, "Vault Deposit under total deposits");
}
function compound() external {
_withdrawRewards();
uint256 balance = cake.balanceOf(address(this));
vault.enterStaking(balance);
}
function updateEstimation() public {
while(block.timestamp > last_payout_calculation + payout_interval){
estimatedPeth = estimatedPeth.add(uint256(prestigeclub.depositSum()).mul(getDailyRate()).div(1e18));
rewardLastEstimation = totalProfit();
last_payout_calculation += payout_interval;
}
}
function setPrestigeClub(address prestige) external onlyOwner {
prestigeclub = IPrestigeClub(prestige);
}
function payoutProvision() external onlyOwner {
_withdrawRewards();
uint256 balance = cake.balanceOf(address(this));
if(balance < ownerProvision){
uint256 left = ownerProvision.sub(balance);
vault.leaveStaking(left);
}
cake.transfer(owner(), ownerProvision);
}
function initialInvest(uint256 amount, uint256 importedRewards) external onlyOwner {
if(importedRewards > 0){
require(alreadyWithdrawn == 0, "Cant import rewards twice");
}
uint256 pending = vault.pendingCake(0, address(this));
//Invest into Masterchef
vault.enterStaking(amount); //Expects that cake already lie on address(this)
alreadyWithdrawn = alreadyWithdrawn.add(pending).add(importedRewards);
depositedCake = depositedCake.add(amount);
}
modifier onlyPrestige() {
require(msg.sender == address(prestigeclub), "Caller not PrestigeClub Contract");
_;
}
// ---- Safety functions -----
function emergencyWithdraw(uint256 amount) external onlyOwner {
vault.leaveStaking(amount);
cake.transfer(owner(), cake.balanceOf(address(this)));
}
function leaveStaking(uint256 amount) external onlyOwner {
vault.leaveStaking(amount);
}
function doEmergencyWithdraw(uint256 _pid) external onlyOwner {
vault.emergencyWithdraw(_pid);
}
function rescueErc20(address token, address addr, uint256 amount) external onlyOwner {
IERC20(token).transfer(addr, amount);
}
function setBaseRate(uint256 _baseRate) external onlyOwner {
require(_baseRate < 2000, "Sanity check"); //Sanity check for Baserate, can´t really be higher than 2000 with current CakeClub model
baseRate = _baseRate;
}
}
|
Note This function is only used by the frontend
|
function outputWithEstimation(uint256 peth) public view returns (uint256){
uint pethEstimation = estimatedPeth;
uint rewards = rewardLastEstimation;
if(dayz > 0){
pethEstimation = pethEstimation.add(uint256(prestigeclub.depositSum()).mul(getDailyRate()).mul(dayz).div(1e18));
rewards = totalProfit();
}
return 1 ether * peth / pethEstimation * rewards / 1 ether;
}
| 1,030,968
|
/**
* Jetoken is looking to fully disrupt the decentralized world with our
new initial Token offering.
If you've an entrepreneurial vision come and join us on our way to success
*/
pragma solidity ^0.8.0;
// SPDX-License-Identifier: Unlicensed
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) {
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 public _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @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;
}
}
// pragma solidity >=0.5.0;
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;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.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;
}
contract Jetoken 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 = 1000000000 * 10**6 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Jetoken";
string private _symbol = "JET";
uint8 private _decimals = 18;
uint256 public _taxFee = 49;
uint256 private _previousTaxFee = _taxFee;
uint256 public _Charity = 1;
uint256 private _previousCharityFee = _Charity;
uint256 public _liquidityFee = 50;
uint256 private _previousLiquidityFee = _liquidityFee;
address public charityAdd = 0xf8685875F38cd961C000f26dD55C49c6f9813593;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
uint256 private numTokensSellToAddToLiquidity = 500000000000 * 10**18;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
event Purchase(address indexed to, uint256 amount);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor () {
_owner = _msgSender();
_rOwned[_owner] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);
// 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;
emit Transfer(address(0),_owner , _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 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 excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
_taxFee = taxFee;
}
function setCharityAdd(address addr) external onlyOwner() {
charityAdd = addr;
}
function setCharityFeePercent(uint256 Charity) external onlyOwner() {
_Charity = Charity;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
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) {
(uint256 tTransferAmount, uint256 tFee, uint256 tburn, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tburn, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tburn, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 charity = calculateCharityFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(charity).sub(tLiquidity);
return (tTransferAmount, tFee, charity, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 charity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rCharity = charity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rCharity);
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 _charity(uint256 charity) private {
uint256 currentRate = _getRate();
uint256 rCharity = charity.mul(currentRate);
_rOwned[charityAdd] = _rOwned[charityAdd].add(rCharity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**3
);
}
function calculateCharityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_Charity).div(
10**3
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**3
);
}
function removeAllFee() private {
if(_taxFee == 0 && _Charity == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousCharityFee = _Charity;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_Charity = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_Charity = _previousCharityFee;
_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);
}
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");
// 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));
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
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);
// 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(!takeFee)
removeAllFee();
_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 charity, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_charity(charity);
_reflectFee(rFee, tFee);
if(!_isExcludedFromFee[sender])
emit Transfer(sender, charityAdd, charity);
emit Transfer(sender, recipient, tTransferAmount);
}
}
|
this method is responsible for taking all fee, if takeFee is true
|
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
_transferStandard(sender, recipient, amount);
if(!takeFee)
restoreAllFee();
}
| 11,702,387
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.7.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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;
}
}
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 IPowerUser {
function usePower(uint256 power) external returns (uint256);
event PowerUsed(address indexed master, uint256 power, string purpose);
}
/**
* @dev Fractal illusion of the ideal stable for the best of cows.
*
* Calmness, deep relaxation, concentration and absolute harmony. Cows just love this place.
* There are rumours, that the place where the stable was built is in fact a source of the power.
* I personally believe that this stable would be perfect for cows to give a lot of amazing milk!
*
* Even mathematics works here differently - cows are not counted like in habitual
* world (like: 1 cow, 2 cows, 3 cows...), but instead they are somehow measured in strange
* unusual large numbers called here "units". Maybe this is just another strange but a sweet dream?..
*/
contract Stable is Ownable {
using SafeMath for uint256;
// Stakeshot contains snapshot aggregated staking history.
struct Stakeshot {
uint256 _block; // number of block stakeshooted
uint256 _cows; // amount of cows in the stable just after the "shoot" moment [units]
uint256 _power; // amount of currently accumulated power available in this block
}
// Precalculate TOTAL_UNITS used for conversion between tokens and units.
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_TOKENS = 21 * 10**6;
uint256 private constant INITIAL_SUPPLY = INITIAL_TOKENS * 10**9;
uint256 private constant TOTAL_UNITS = MAX_UINT256 - (MAX_UINT256 % INITIAL_SUPPLY);
uint256 private constant COWS_TO_POWER_DELIMETER = 10**27;
// COW token is hardcoded into the stable.
IERC20 private _tokenCOW = IERC20(0xf0be50ED0620E0Ba60CA7FC968eD14762e0A5Dd3);
// Amount of cows by masters and total amount of cows in the stable.
mapping(address => uint256) private _cows; // [units]
uint256 private _totalCows; // [units]
// Most actual stakeshots by masters.
mapping(address => Stakeshot) private _stakeshots;
uint256 private _totalPower;
event CowsArrived(address indexed master, uint256 cows);
event CowsLeaved(address indexed master, uint256 cows);
function driveCowsInto(uint256 cows) external {
address master = msg.sender;
// Transport provided cows to the stable
bool ok = _tokenCOW.transferFrom(master, address(this), cows);
require(ok, "Stable: unable to transport cows to the stable");
// Register each arrived cow
uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply());
uint256 units = cows.mul(unitsPerCow);
_cows[master] = _cows[master].add(units);
_totalCows = _totalCows.add(units);
// Recalculate power collected by the master
_updateStakeshot(master);
// Emit event to the logs so can be effectively used later
emit CowsArrived(master, cows);
}
function driveCowsOut(address master, uint256 cows) external {
// Transport requested cows from the stable
bool ok = _tokenCOW.transfer(master, cows);
require(ok, "Stable: unable to transport cows from the stable");
// Unregister each leaving cow
uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply());
uint256 units = cows.mul(unitsPerCow);
_cows[master] = _cows[master].sub(units);
_totalCows = _totalCows.sub(units);
// Recalculate power collected by the master
_updateStakeshot(master);
// Emit event to the logs so can be effectively used later
emit CowsLeaved(master, cows);
}
function token() public view returns (IERC20) {
return _tokenCOW;
}
function cows(address master) public view returns (uint256) {
uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply());
return _cows[master].div(unitsPerCow);
}
function totalCows() public view returns (uint256) {
uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply());
return _totalCows.div(unitsPerCow);
}
function power(address master) public view returns (uint256, uint256) {
return (_stakeshots[master]._block, _stakeshots[master]._power);
}
function totalPower() public view returns (uint256) {
return _totalPower;
}
function stakeshot(address master) public view returns (uint256, uint256, uint256) {
uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply());
Stakeshot storage s = _stakeshots[master];
return (s._block, s._cows.div(unitsPerCow), s._power);
}
function _updateStakeshot(address master) private {
Stakeshot storage s = _stakeshots[master];
uint256 duration = block.number.sub(s._block);
if (s._block > 0 && duration > 0) {
// Recalculate collected power
uint256 productivity = s._cows.div(COWS_TO_POWER_DELIMETER);
uint256 powerGained = productivity.mul(duration);
s._power = s._power.add(powerGained);
_totalPower = _totalPower.add(powerGained);
}
s._block = block.number;
s._cows = _cows[master];
}
}
|
Transport provided cows to the stable Register each arrived cow Recalculate power collected by the master Emit event to the logs so can be effectively used later
|
function driveCowsInto(uint256 cows) external {
address master = msg.sender;
bool ok = _tokenCOW.transferFrom(master, address(this), cows);
require(ok, "Stable: unable to transport cows to the stable");
uint256 unitsPerCow = TOTAL_UNITS.div(_tokenCOW.totalSupply());
uint256 units = cows.mul(unitsPerCow);
_cows[master] = _cows[master].add(units);
_totalCows = _totalCows.add(units);
_updateStakeshot(master);
emit CowsArrived(master, cows);
}
| 8,042,045
|
/**
*Submitted for verification at Etherscan.io on 2020-07-28
*/
pragma solidity 0.6.0;
/**
* @title ETH bonus pool
* @dev ETH collection and inquiry
*/
contract Nest_3_Abonus {
using address_make_payable for address;
using SafeMath for uint256;
Nest_3_VoteFactory _voteFactory; // Voting contract
address _nestAddress; // NEST contract address
mapping (address => uint256) ethMapping; // ETH bonus ledger of corresponding tokens
uint256 _mostDistribution = 40; // The highest allocation ratio of NEST bonus pool
uint256 _leastDistribution = 20; // The lowest allocation ratio of NEST bonus pool
uint256 _distributionTime = 1200000; // The decay time interval of NEST bonus pool allocation ratio
uint256 _distributionSpan = 5; // The decay degree of NEST bonus pool allocation ratio
/**
* @dev Initialization method
* @param voteFactory Voting contract address
*/
constructor(address voteFactory) public {
_voteFactory = Nest_3_VoteFactory(voteFactory);
_nestAddress = address(_voteFactory.checkAddress("nest"));
}
/**
* @dev Reset voting contract
* @param voteFactory Voting contract address
*/
function changeMapping(address voteFactory) public onlyOwner{
_voteFactory = Nest_3_VoteFactory(voteFactory);
_nestAddress = address(_voteFactory.checkAddress("nest"));
}
/**
* @dev Transfer in bonus
* @param token Corresponding to lock-up Token
*/
function switchToEth(address token) public payable {
ethMapping[token] = ethMapping[token].add(msg.value);
}
/**
* @dev Transferin bonus - NToken offering fee
* @param token Corresponding to lock-up NToken
*/
function switchToEthForNTokenOffer(address token) public payable {
Nest_NToken nToken = Nest_NToken(token);
(uint256 createBlock,) = nToken.checkBlockInfo();
uint256 subBlock = block.number.sub(createBlock);
uint256 times = subBlock.div(_distributionTime);
uint256 distributionValue = times.mul(_distributionSpan);
uint256 distribution = _mostDistribution;
if (_leastDistribution.add(distributionValue) > _mostDistribution) {
distribution = _leastDistribution;
} else {
distribution = _mostDistribution.sub(distributionValue);
}
uint256 nestEth = msg.value.mul(distribution).div(100);
ethMapping[_nestAddress] = ethMapping[_nestAddress].add(nestEth);
ethMapping[token] = ethMapping[token].add(msg.value.sub(nestEth));
}
/**
* @dev Receive ETH
* @param num Receive amount
* @param token Correspond to locked Token
* @param target Transfer target
*/
function getETH(uint256 num, address token, address target) public onlyContract {
require(num <= ethMapping[token], "Insufficient storage balance");
ethMapping[token] = ethMapping[token].sub(num); //injected INTEGER OVERFLOW OR UNDERFLOW
address payable addr = target.make_payable();
addr.transfer(num);
}
/**
* @dev Get bonus pool balance
* @param token Corresponded locked Token
* @return uint256 Bonus pool balance
*/
function getETHNum(address token) public view returns (uint256) {
return ethMapping[token];
}
// View NEST address
function checkNestAddress() public view returns(address) {
return _nestAddress;
}
// View the highest NEST bonus pool allocation ratio
function checkMostDistribution() public view returns(uint256) {
return _mostDistribution;
}
// View the lowest NEST bonus pool allocation ratio
function checkLeastDistribution() public view returns(uint256) {
return _leastDistribution;
}
// View the decay time interval of NEST bonus pool allocation ratio
function checkDistributionTime() public view returns(uint256) {
return _distributionTime;
}
// View the decay degree of NEST bonus pool allocation ratio
function checkDistributionSpan() public view returns(uint256) {
return _distributionSpan;
}
// Modify the highest NEST bonus pool allocation ratio
function changeMostDistribution(uint256 num) public onlyOwner {
_mostDistribution = num;
}
// Modify the lowest NEST bonus pool allocation ratio
function changeLeastDistribution(uint256 num) public onlyOwner {
_leastDistribution = num;
}
// Modify the decay time interval of NEST bonus pool allocation ratio
function changeDistributionTime(uint256 num) public onlyOwner {
_distributionTime = num;
}
// Modify the decay degree of NEST bonus pool allocation ratio
function changeDistributionSpan(uint256 num) public onlyOwner {
_distributionSpan = num;
}
// Withdraw ETH
function turnOutAllEth(uint256 amount, address target) public onlyOwner {
address payable addr = target.make_payable();
addr.transfer(amount);
}
// Only bonus logic contract
modifier onlyContract(){
require(_voteFactory.checkAddress("nest.v3.tokenAbonus") == address(msg.sender), "No authority");
_;
}
// Administrator only
modifier onlyOwner(){
require(_voteFactory.checkOwners(address(msg.sender)), "No authority");
_;
}
}
// Voting factory
interface Nest_3_VoteFactory {
// Check address
function checkAddress(string calldata name) external view returns (address contractAddress);
// Check whether the administrator
function checkOwners(address man) external view returns (bool);
}
// NToken
interface Nest_NToken {
// Increase token
function increaseTotal(uint256 value) external;
// Query mining information
function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock);
// Query creator
function checkOwner() external view returns(address);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
//require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library address_make_payable {
function make_payable(address x) internal pure returns (address payable) {
return address(uint160(x));
}
}
|
View the decay time interval of NEST bonus pool allocation ratio
|
function checkDistributionTime() public view returns(uint256) {
return _distributionTime;
}
| 2,552,220
|
./full_match/80001/0x8B08174c8EdEF49fB218Ac26f5768E16cDDA73F2/sources/contracts/Deps/hats-protocol/lib/ERC1155/ERC1155.sol
|
An array can't have a total length larger than the max uint256 value.
|
function _batchMint(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(idsLength == amounts.length, "LENGTH_MISMATCH");
for (uint256 i = 0; i < idsLength; ) {
_balanceOf[to][ids[i]] += amounts[i];
unchecked {
++i;
}
}
emit TransferBatch(msg.sender, address(0), to, ids, amounts);
require(
to.code.length == 0
? to != address(0)
: ERC1155TokenReceiver(to).onERC1155BatchReceived(msg.sender, address(0), ids, amounts, data) ==
ERC1155TokenReceiver.onERC1155BatchReceived.selector,
"UNSAFE_RECIPIENT"
);
}
| 5,576,768
|
./partial_match/83/0x7473a3E6f3d7A4F33F59345E971D2d04d1fe299F/sources/Bridge.sol
|
Get validators by specifying an offset index and a chunk's size. offset An offset index of validators mapping. size The size of the validators chunk. return an empty list reduce size of the entire list
|
function getValidators(uint256 offset, uint256 size) public view returns(ValidatorWithPower[] memory) {
ValidatorWithPower[] memory validatorWithPowerList;
uint256 numberOfValidators = getNumberOfValidators();
if (offset >= numberOfValidators) {
return validatorWithPowerList;
size = numberOfValidators - offset;
}
validatorWithPowerList = new ValidatorWithPower[](size);
for (uint256 idx = 0; idx < size; ++idx) {
(address addr, uint256 power) = validatorPowers.at(idx + offset);
}
return validatorWithPowerList;
}
| 8,828,943
|
pragma solidity ^0.4.18;
/**
* @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);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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);
}
contract Hive is ERC20 {
using SafeMath for uint;
string public constant name = "UHIVE";
string public constant symbol = "HVE";
uint256 public constant decimals = 18;
uint256 _totalSupply = 80000000000 * (10**decimals);
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
// Balances for each account
mapping(address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
// Owner of this contract
address public owner;
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function changeOwner(address _newOwner) onlyOwner public {
require(_newOwner != address(0));
owner = _newOwner;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function isFrozenAccount(address _addr) public constant returns (bool) {
return frozenAccount[_addr];
}
function destroyCoins(address addressToDestroy, uint256 amount) onlyOwner public {
require(addressToDestroy != address(0));
require(amount > 0);
require(amount <= balances[addressToDestroy]);
balances[addressToDestroy] -= amount;
_totalSupply -= amount;
}
// Constructor
function Hive() public {
owner = msg.sender;
balances[owner] = _totalSupply;
}
function totalSupply() public constant returns (uint256 supply) {
supply = _totalSupply;
}
// What is the balance of a particular account?
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
// Transfer the balance from owner's account to another account
function transfer(address _to, uint256 _value) public returns (bool success) {
if (_to != address(0) && isFrozenAccount(msg.sender) == false && balances[msg.sender] >= _value && _value > 0 && balances[_to].add(_value) > balances[_to]) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(address _from,address _to, uint256 _value) public returns (bool success) {
if (_to != address(0) && isFrozenAccount(_from) == false && balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to].add(_value) > balances[_to]) {
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract UhiveVest {
using SafeMath for uint256;
// The token being sold
Hive public token;
// Owner of this contract
address public owner;
uint256 public releaseDate;
// Functions with this modifier can only be executed when the vesting period elapses
modifier onlyWhenReleased {
require(now >= releaseDate);
_;
}
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function UhiveVest(Hive _token, uint256 _releaseDate) public {
token = _token;
owner = msg.sender;
releaseDate = _releaseDate;
}
function () external payable {
_forwardFunds();
}
function _forwardFunds() private {
owner.transfer(msg.value);
}
/**
* Event for token transfer logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenTransfer(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
//Transfer tokens to a specified address, works only after vesting period elapses
function forwardTokens(address _beneficiary, uint256 totalTokens) onlyOwner onlyWhenReleased public {
_preValidateTokenTransfer(_beneficiary, totalTokens);
_deliverTokens(_beneficiary, totalTokens);
}
//Withdraw tokens to owner wallet, works only after vesting period elapses
function withdrawTokens() onlyOwner onlyWhenReleased public {
uint256 unsold = token.balanceOf(this);
token.transfer(owner, unsold);
}
//Change the owner wallet address
function changeOwner(address _newOwner) onlyOwner public {
require(_newOwner != address(0));
owner = _newOwner;
}
//Self-destruct the contract, contract cannot be destroyed until the vesting period is over.
function terminate() public onlyOwner onlyWhenReleased {
selfdestruct(owner);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
//Assertain the validity of the transfer
function _preValidateTokenTransfer(address _beneficiary, uint256 _tokenAmount) internal pure {
require(_beneficiary != address(0));
require(_tokenAmount > 0);
}
//Forward the tokens from the contract to the beneficiary
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
TokenTransfer(msg.sender, _beneficiary, 0, _tokenAmount);
}
}
|
Transfer tokens to a specified address, works only after vesting period elapses
|
function forwardTokens(address _beneficiary, uint256 totalTokens) onlyOwner onlyWhenReleased public {
_preValidateTokenTransfer(_beneficiary, totalTokens);
_deliverTokens(_beneficiary, totalTokens);
}
| 252,496
|
/**
* SPDX-License-Identifier: UNLICENSED
*/
pragma solidity =0.6.10;
pragma experimental ABIEncoderV2;
import {OwnableUpgradeSafe} from "./packages/oz/upgradeability/OwnableUpgradeSafe.sol";
import {ReentrancyGuardUpgradeSafe} from "./packages/oz/upgradeability/ReentrancyGuardUpgradeSafe.sol";
import {Initializable} from "./packages/oz/upgradeability/Initializable.sol";
import {SafeMath} from "./packages/oz/SafeMath.sol";
import {MarginVault} from "./libs/MarginVault.sol";
import {Actions} from "./libs/Actions.sol";
import {AddressBookInterface} from "./interfaces/AddressBookInterface.sol";
import {OtokenInterface} from "./interfaces/OtokenInterface.sol";
import {MarginCalculatorInterface} from "./interfaces/MarginCalculatorInterface.sol";
import {OracleInterface} from "./interfaces/OracleInterface.sol";
import {WhitelistInterface} from "./interfaces/WhitelistInterface.sol";
import {MarginPoolInterface} from "./interfaces/MarginPoolInterface.sol";
import {CalleeInterface} from "./interfaces/CalleeInterface.sol";
/**
* @title Controller
* @author Opyn Team
* @notice Contract that controls the Gamma Protocol and the interaction of all sub contracts
*/
contract Controller is Initializable, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe {
using MarginVault for MarginVault.Vault;
using SafeMath for uint256;
AddressBookInterface public addressbook;
WhitelistInterface public whitelist;
OracleInterface public oracle;
MarginCalculatorInterface public calculator;
MarginPoolInterface public pool;
///@dev scale used in MarginCalculator
uint256 internal constant BASE = 8;
/// @notice address that has permission to partially pause the system, where system functionality is paused
/// except redeem and settleVault
address public partialPauser;
/// @notice address that has permission to fully pause the system, where all system functionality is paused
address public fullPauser;
/// @notice True if all system functionality is paused other than redeem and settle vault
bool public systemPartiallyPaused;
/// @notice True if all system functionality is paused
bool public systemFullyPaused;
/// @notice True if a call action can only be executed to a whitelisted callee
bool public callRestricted;
/// @dev mapping between an owner address and the number of owner address vaults
mapping(address => uint256) internal accountVaultCounter;
/// @dev mapping between an owner address and a specific vault using a vault id
mapping(address => mapping(uint256 => MarginVault.Vault)) internal vaults;
/// @dev mapping between an account owner and their approved or unapproved account operators
mapping(address => mapping(address => bool)) internal operators;
/// @notice emits an event when an account operator is updated for a specific account owner
event AccountOperatorUpdated(address indexed accountOwner, address indexed operator, bool isSet);
/// @notice emits an event when a new vault is opened
event VaultOpened(address indexed accountOwner, uint256 vaultId);
/// @notice emits an event when a long oToken is deposited into a vault
event LongOtokenDeposited(
address indexed otoken,
address indexed accountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a long oToken is withdrawn from a vault
event LongOtokenWithdrawed(
address indexed otoken,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a collateral asset is deposited into a vault
event CollateralAssetDeposited(
address indexed asset,
address indexed accountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a collateral asset is withdrawn from a vault
event CollateralAssetWithdrawed(
address indexed asset,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a short oToken is minted from a vault
event ShortOtokenMinted(
address indexed otoken,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a short oToken is burned
event ShortOtokenBurned(
address indexed otoken,
address indexed AccountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when an oToken is redeemed
event Redeem(
address indexed otoken,
address indexed redeemer,
address indexed receiver,
address collateralAsset,
uint256 otokenBurned,
uint256 payout
);
/// @notice emits an event when a vault is settled
event VaultSettled(
address indexed AccountOwner,
address indexed to,
address indexed otoken,
uint256 vaultId,
uint256 payout
);
/// @notice emits an event when a call action is executed
event CallExecuted(address indexed from, address indexed to, bytes data);
/// @notice emits an event when the fullPauser address changes
event FullPauserUpdated(address indexed oldFullPauser, address indexed newFullPauser);
/// @notice emits an event when the partialPauser address changes
event PartialPauserUpdated(address indexed oldPartialPauser, address indexed newPartialPauser);
/// @notice emits an event when the system partial paused status changes
event SystemPartiallyPaused(bool isPaused);
/// @notice emits an event when the system fully paused status changes
event SystemFullyPaused(bool isPaused);
/// @notice emits an event when the call action restriction changes
event CallRestricted(bool isRestricted);
/**
* @notice modifier to check if the system is not partially paused, where only redeem and settleVault is allowed
*/
modifier notPartiallyPaused {
_isNotPartiallyPaused();
_;
}
/**
* @notice modifier to check if the system is not fully paused, where no functionality is allowed
*/
modifier notFullyPaused {
_isNotFullyPaused();
_;
}
/**
* @notice modifier to check if sender is the fullPauser address
*/
modifier onlyFullPauser {
require(msg.sender == fullPauser, "Controller: sender is not fullPauser");
_;
}
/**
* @notice modifier to check if the sender is the partialPauser address
*/
modifier onlyPartialPauser {
require(msg.sender == partialPauser, "Controller: sender is not partialPauser");
_;
}
/**
* @notice modifier to check if the sender is the account owner or an approved account operator
* @param _sender sender address
* @param _accountOwner account owner address
*/
modifier onlyAuthorized(address _sender, address _accountOwner) {
_isAuthorized(_sender, _accountOwner);
_;
}
/**
* @notice modifier to check if the called address is a whitelisted callee address
* @param _callee called address
*/
modifier onlyWhitelistedCallee(address _callee) {
if (callRestricted) {
require(_isCalleeWhitelisted(_callee), "Controller: callee is not a whitelisted address");
}
_;
}
/**
* @dev check if the system is not in a partiallyPaused state
*/
function _isNotPartiallyPaused() internal view {
require(!systemPartiallyPaused, "Controller: system is partially paused");
}
/**
* @dev check if the system is not in an fullyPaused state
*/
function _isNotFullyPaused() internal view {
require(!systemFullyPaused, "Controller: system is fully paused");
}
/**
* @dev check if the sender is an authorized operator
* @param _sender msg.sender
* @param _accountOwner owner of a vault
*/
function _isAuthorized(address _sender, address _accountOwner) internal view {
require(
(_sender == _accountOwner) || (operators[_accountOwner][_sender]),
"Controller: msg.sender is not authorized to run action"
);
}
/**
* @notice initalize the deployed contract
* @param _addressBook addressbook module
* @param _owner account owner address
*/
function initialize(address _addressBook, address _owner) external initializer {
require(_addressBook != address(0), "Controller: invalid addressbook address");
require(_owner != address(0), "Controller: invalid owner address");
__Ownable_init(_owner);
__ReentrancyGuard_init_unchained();
addressbook = AddressBookInterface(_addressBook);
_refreshConfigInternal();
}
/**
* @notice allows the partialPauser to toggle the systemPartiallyPaused variable and partially pause or partially unpause the system
* @dev can only be called by the partialPauser
* @param _partiallyPaused new boolean value to set systemPartiallyPaused to
*/
function setSystemPartiallyPaused(bool _partiallyPaused) external onlyPartialPauser {
require(systemPartiallyPaused != _partiallyPaused, "Controller: invalid input");
systemPartiallyPaused = _partiallyPaused;
emit SystemPartiallyPaused(systemPartiallyPaused);
}
/**
* @notice allows the fullPauser to toggle the systemFullyPaused variable and fully pause or fully unpause the system
* @dev can only be called by the fullPauser
* @param _fullyPaused new boolean value to set systemFullyPaused to
*/
function setSystemFullyPaused(bool _fullyPaused) external onlyFullPauser {
require(systemFullyPaused != _fullyPaused, "Controller: invalid input");
systemFullyPaused = _fullyPaused;
emit SystemFullyPaused(systemFullyPaused);
}
/**
* @notice allows the owner to set the fullPauser address
* @dev can only be called by the owner
* @param _fullPauser new fullPauser address
*/
function setFullPauser(address _fullPauser) external onlyOwner {
require(_fullPauser != address(0), "Controller: fullPauser cannot be set to address zero");
require(fullPauser != _fullPauser, "Controller: invalid input");
emit FullPauserUpdated(fullPauser, _fullPauser);
fullPauser = _fullPauser;
}
/**
* @notice allows the owner to set the partialPauser address
* @dev can only be called by the owner
* @param _partialPauser new partialPauser address
*/
function setPartialPauser(address _partialPauser) external onlyOwner {
require(_partialPauser != address(0), "Controller: partialPauser cannot be set to address zero");
require(partialPauser != _partialPauser, "Controller: invalid input");
emit PartialPauserUpdated(partialPauser, _partialPauser);
partialPauser = _partialPauser;
}
/**
* @notice allows the owner to toggle the restriction on whitelisted call actions and only allow whitelisted
* call addresses or allow any arbitrary call addresses
* @dev can only be called by the owner
* @param _isRestricted new call restriction state
*/
function setCallRestriction(bool _isRestricted) external onlyOwner {
require(callRestricted != _isRestricted, "Controller: invalid input");
callRestricted = _isRestricted;
emit CallRestricted(callRestricted);
}
/**
* @notice allows a user to give or revoke privileges to an operator which can act on their behalf on their vaults
* @dev can only be updated by the vault owner
* @param _operator operator that the sender wants to give privileges to or revoke them from
* @param _isOperator new boolean value that expresses if the sender is giving or revoking privileges for _operator
*/
function setOperator(address _operator, bool _isOperator) external {
require(operators[msg.sender][_operator] != _isOperator, "Controller: invalid input");
operators[msg.sender][_operator] = _isOperator;
emit AccountOperatorUpdated(msg.sender, _operator, _isOperator);
}
/**
* @dev updates the configuration of the controller. can only be called by the owner
*/
function refreshConfiguration() external onlyOwner {
_refreshConfigInternal();
}
/**
* @notice execute a number of actions on specific vaults
* @dev can only be called when the system is not fully paused
* @param _actions array of actions arguments
*/
function operate(Actions.ActionArgs[] memory _actions) external nonReentrant notFullyPaused {
(bool vaultUpdated, address vaultOwner, uint256 vaultId) = _runActions(_actions);
if (vaultUpdated) _verifyFinalState(vaultOwner, vaultId);
}
/**
* @notice check if a specific address is an operator for an owner account
* @param _owner account owner address
* @param _operator account operator address
* @return True if the _operator is an approved operator for the _owner account
*/
function isOperator(address _owner, address _operator) external view returns (bool) {
return operators[_owner][_operator];
}
/**
* @notice returns the current controller configuration
* @return whitelist, the address of the whitelist module
* @return oracle, the address of the oracle module
* @return calculator, the address of the calculator module
* @return pool, the address of the pool module
*/
function getConfiguration()
external
view
returns (
address,
address,
address,
address
)
{
return (address(whitelist), address(oracle), address(calculator), address(pool));
}
/**
* @notice return a vault's proceeds pre or post expiry, the amount of collateral that can be removed from a vault
* @param _owner account owner of the vault
* @param _vaultId vaultId to return balances for
* @return amount of collateral that can be taken out
*/
function getProceed(address _owner, uint256 _vaultId) external view returns (uint256) {
MarginVault.Vault memory vault = getVault(_owner, _vaultId);
(uint256 netValue, ) = calculator.getExcessCollateral(vault);
return netValue;
}
/**
* @notice get an oToken's payout/cash value after expiry, in the collateral asset
* @param _otoken oToken address
* @param _amount amount of the oToken to calculate the payout for, always represented in 1e8
* @return amount of collateral to pay out
*/
function getPayout(address _otoken, uint256 _amount) public view returns (uint256) {
uint256 rate = calculator.getExpiredPayoutRate(_otoken);
return rate.mul(_amount).div(10**BASE);
}
/**
* @dev return if an expired oToken contract’s settlement price has been finalized
* @param _otoken address of the oToken
* @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not
*/
function isSettlementAllowed(address _otoken) public view returns (bool) {
OtokenInterface otoken = OtokenInterface(_otoken);
address underlying = otoken.underlyingAsset();
address strike = otoken.strikeAsset();
address collateral = otoken.collateralAsset();
uint256 expiry = otoken.expiryTimestamp();
bool isUnderlyingFinalized = oracle.isDisputePeriodOver(underlying, expiry);
bool isStrikeFinalized = oracle.isDisputePeriodOver(strike, expiry);
bool isCollateralFinalized = oracle.isDisputePeriodOver(collateral, expiry);
return isUnderlyingFinalized && isStrikeFinalized && isCollateralFinalized;
}
/**
* @notice get the number of vaults for a specified account owner
* @param _accountOwner account owner address
* @return number of vaults
*/
function getAccountVaultCounter(address _accountOwner) external view returns (uint256) {
return accountVaultCounter[_accountOwner];
}
/**
* @notice check if an oToken has expired
* @param _otoken oToken address
* @return True if the otoken has expired, False if not
*/
function hasExpired(address _otoken) external view returns (bool) {
uint256 otokenExpiryTimestamp = OtokenInterface(_otoken).expiryTimestamp();
return now >= otokenExpiryTimestamp;
}
/**
* @notice return a specific vault
* @param _owner account owner
* @param _vaultId vault id of vault to return
* @return Vault struct that corresponds to the _vaultId of _owner
*/
function getVault(address _owner, uint256 _vaultId) public view returns (MarginVault.Vault memory) {
return vaults[_owner][_vaultId];
}
/**
* @notice execute a variety of actions
* @dev for each action in the action array, execute the corresponding action, only one vault can be modified
* for all actions except SettleVault, Redeem, and Call
* @param _actions array of type Actions.ActionArgs[], which expresses which actions the user wants to execute
* @return vaultUpdated, indicates if a vault has changed
* @return owner, the vault owner if a vault has changed
* @return vaultId, the vault Id if a vault has changed
*/
function _runActions(Actions.ActionArgs[] memory _actions)
internal
returns (
bool,
address,
uint256
)
{
address vaultOwner;
uint256 vaultId;
bool vaultUpdated;
for (uint256 i = 0; i < _actions.length; i++) {
Actions.ActionArgs memory action = _actions[i];
Actions.ActionType actionType = action.actionType;
if (
(actionType != Actions.ActionType.SettleVault) &&
(actionType != Actions.ActionType.Redeem) &&
(actionType != Actions.ActionType.Call)
) {
// check if this action is manipulating the same vault as all other actions, if a vault has already been updated
if (vaultUpdated) {
require(vaultOwner == action.owner, "Controller: can not run actions for different owners");
require(vaultId == action.vaultId, "Controller: can not run actions on different vaults");
}
vaultUpdated = true;
vaultId = action.vaultId;
vaultOwner = action.owner;
}
if (actionType == Actions.ActionType.OpenVault) {
_openVault(Actions._parseOpenVaultArgs(action));
} else if (actionType == Actions.ActionType.DepositLongOption) {
_depositLong(Actions._parseDepositArgs(action));
} else if (actionType == Actions.ActionType.WithdrawLongOption) {
_withdrawLong(Actions._parseWithdrawArgs(action));
} else if (actionType == Actions.ActionType.DepositCollateral) {
_depositCollateral(Actions._parseDepositArgs(action));
} else if (actionType == Actions.ActionType.WithdrawCollateral) {
_withdrawCollateral(Actions._parseWithdrawArgs(action));
} else if (actionType == Actions.ActionType.MintShortOption) {
_mintOtoken(Actions._parseMintArgs(action));
} else if (actionType == Actions.ActionType.BurnShortOption) {
_burnOtoken(Actions._parseBurnArgs(action));
} else if (actionType == Actions.ActionType.Redeem) {
_redeem(Actions._parseRedeemArgs(action));
} else if (actionType == Actions.ActionType.SettleVault) {
_settleVault(Actions._parseSettleVaultArgs(action));
} else if (actionType == Actions.ActionType.Call) {
_call(Actions._parseCallArgs(action));
}
}
return (vaultUpdated, vaultOwner, vaultId);
}
/**
* @notice verify the vault final state after executing all actions
* @param _owner account owner address
* @param _vaultId vault id of the final vault
*/
function _verifyFinalState(address _owner, uint256 _vaultId) internal view {
MarginVault.Vault memory _vault = getVault(_owner, _vaultId);
(, bool isValidVault) = calculator.getExcessCollateral(_vault);
require(isValidVault, "Controller: invalid final vault state");
}
/**
* @notice open a new vault inside an account
* @dev only the account owner or operator can open a vault, cannot be called when system is partiallyPaused or fullyPaused
* @param _args OpenVaultArgs structure
*/
function _openVault(Actions.OpenVaultArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
accountVaultCounter[_args.owner] = accountVaultCounter[_args.owner].add(1);
require(
_args.vaultId == accountVaultCounter[_args.owner],
"Controller: can not run actions on inexistent vault"
);
emit VaultOpened(_args.owner, accountVaultCounter[_args.owner]);
}
/**
* @notice deposit a long oToken into a vault
* @dev only the account owner or operator can deposit a long oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args DepositArgs structure
*/
function _depositLong(Actions.DepositArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
require(
(_args.from == msg.sender) || (_args.from == _args.owner),
"Controller: cannot deposit long otoken from this address"
);
require(
whitelist.isWhitelistedOtoken(_args.asset),
"Controller: otoken is not whitelisted to be used as collateral"
);
OtokenInterface otoken = OtokenInterface(_args.asset);
require(now < otoken.expiryTimestamp(), "Controller: otoken used as collateral is already expired");
vaults[_args.owner][_args.vaultId].addLong(_args.asset, _args.amount, _args.index);
pool.transferToPool(_args.asset, _args.from, _args.amount);
emit LongOtokenDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice withdraw a long oToken from a vault
* @dev only the account owner or operator can withdraw a long oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args WithdrawArgs structure
*/
function _withdrawLong(Actions.WithdrawArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
OtokenInterface otoken = OtokenInterface(_args.asset);
require(now < otoken.expiryTimestamp(), "Controller: can not withdraw an expired otoken");
vaults[_args.owner][_args.vaultId].removeLong(_args.asset, _args.amount, _args.index);
pool.transferToUser(_args.asset, _args.to, _args.amount);
emit LongOtokenWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice deposit a collateral asset into a vault
* @dev only the account owner or operator can deposit collateral, cannot be called when system is partiallyPaused or fullyPaused
* @param _args DepositArgs structure
*/
function _depositCollateral(Actions.DepositArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
require(
(_args.from == msg.sender) || (_args.from == _args.owner),
"Controller: cannot deposit collateral from this address"
);
require(
whitelist.isWhitelistedCollateral(_args.asset),
"Controller: asset is not whitelisted to be used as collateral"
);
vaults[_args.owner][_args.vaultId].addCollateral(_args.asset, _args.amount, _args.index);
pool.transferToPool(_args.asset, _args.from, _args.amount);
emit CollateralAssetDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice withdraw a collateral asset from a vault
* @dev only the account owner or operator can withdraw collateral, cannot be called when system is partiallyPaused or fullyPaused
* @param _args WithdrawArgs structure
*/
function _withdrawCollateral(Actions.WithdrawArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
MarginVault.Vault memory vault = getVault(_args.owner, _args.vaultId);
if (_isNotEmpty(vault.shortOtokens)) {
OtokenInterface otoken = OtokenInterface(vault.shortOtokens[0]);
require(
now < otoken.expiryTimestamp(),
"Controller: can not withdraw collateral from a vault with an expired short otoken"
);
}
vaults[_args.owner][_args.vaultId].removeCollateral(_args.asset, _args.amount, _args.index);
pool.transferToUser(_args.asset, _args.to, _args.amount);
emit CollateralAssetWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice mint short oTokens from a vault which creates an obligation that is recorded in the vault
* @dev only the account owner or operator can mint an oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args MintArgs structure
*/
function _mintOtoken(Actions.MintArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
require(whitelist.isWhitelistedOtoken(_args.otoken), "Controller: otoken is not whitelisted to be minted");
OtokenInterface otoken = OtokenInterface(_args.otoken);
require(now < otoken.expiryTimestamp(), "Controller: can not mint expired otoken");
vaults[_args.owner][_args.vaultId].addShort(_args.otoken, _args.amount, _args.index);
otoken.mintOtoken(_args.to, _args.amount);
emit ShortOtokenMinted(_args.otoken, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice burn oTokens to reduce or remove the minted oToken obligation recorded in a vault
* @dev only the account owner or operator can burn an oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args MintArgs structure
*/
function _burnOtoken(Actions.BurnArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
require((_args.from == msg.sender) || (_args.from == _args.owner), "Controller: cannot burn from this address");
OtokenInterface otoken = OtokenInterface(_args.otoken);
require(now < otoken.expiryTimestamp(), "Controller: can not burn expired otoken");
vaults[_args.owner][_args.vaultId].removeShort(_args.otoken, _args.amount, _args.index);
otoken.burnOtoken(_args.from, _args.amount);
emit ShortOtokenBurned(_args.otoken, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice redeem an oToken after expiry, receiving the payout of the oToken in the collateral asset
* @dev cannot be called when system is fullyPaused
* @param _args RedeemArgs structure
*/
function _redeem(Actions.RedeemArgs memory _args) internal {
OtokenInterface otoken = OtokenInterface(_args.otoken);
require(whitelist.isWhitelistedOtoken(_args.otoken), "Controller: otoken is not whitelisted to be redeemed");
require(now >= otoken.expiryTimestamp(), "Controller: can not redeem un-expired otoken");
require(isSettlementAllowed(_args.otoken), "Controller: asset prices not finalized yet");
uint256 payout = getPayout(_args.otoken, _args.amount);
otoken.burnOtoken(msg.sender, _args.amount);
pool.transferToUser(otoken.collateralAsset(), _args.receiver, payout);
emit Redeem(_args.otoken, msg.sender, _args.receiver, otoken.collateralAsset(), _args.amount, payout);
}
/**
* @notice settle a vault after expiry, removing the net proceeds/collateral after both long and short oToken payouts have settled
* @dev deletes a vault of vaultId after net proceeds/collateral is removed, cannot be called when system is fullyPaused
* @param _args SettleVaultArgs structure
*/
function _settleVault(Actions.SettleVaultArgs memory _args) internal onlyAuthorized(msg.sender, _args.owner) {
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
MarginVault.Vault memory vault = getVault(_args.owner, _args.vaultId);
bool hasShort = _isNotEmpty(vault.shortOtokens);
bool hasLong = _isNotEmpty(vault.longOtokens);
require(hasShort || hasLong, "Controller: Can't settle vault with no otoken");
OtokenInterface otoken = hasShort
? OtokenInterface(vault.shortOtokens[0])
: OtokenInterface(vault.longOtokens[0]);
require(now >= otoken.expiryTimestamp(), "Controller: can not settle vault with un-expired otoken");
require(isSettlementAllowed(address(otoken)), "Controller: asset prices not finalized yet");
(uint256 payout, ) = calculator.getExcessCollateral(vault);
if (hasLong) {
OtokenInterface longOtoken = OtokenInterface(vault.longOtokens[0]);
longOtoken.burnOtoken(address(pool), vault.longAmounts[0]);
}
delete vaults[_args.owner][_args.vaultId];
pool.transferToUser(otoken.collateralAsset(), _args.to, payout);
emit VaultSettled(_args.owner, _args.to, address(otoken), _args.vaultId, payout);
}
/**
* @notice execute arbitrary calls
* @dev cannot be called when system is partiallyPaused or fullyPaused
* @param _args Call action
*/
function _call(Actions.CallArgs memory _args)
internal
notPartiallyPaused
onlyWhitelistedCallee(_args.callee)
returns (uint256)
{
CalleeInterface(_args.callee).callFunction(msg.sender, _args.data);
emit CallExecuted(msg.sender, _args.callee, _args.data);
}
/**
* @notice check if a vault id is valid for a given account owner address
* @param _accountOwner account owner address
* @param _vaultId vault id to check
* @return True if the _vaultId is valid, False if not
*/
function _checkVaultId(address _accountOwner, uint256 _vaultId) internal view returns (bool) {
return ((_vaultId > 0) && (_vaultId <= accountVaultCounter[_accountOwner]));
}
function _isNotEmpty(address[] memory _array) internal pure returns (bool) {
return (_array.length > 0) && (_array[0] != address(0));
}
/**
* @notice return if a callee address is whitelisted or not
* @param _callee callee address
* @return True if callee address is whitelisted, False if not
*/
function _isCalleeWhitelisted(address _callee) internal view returns (bool) {
return whitelist.isWhitelistedCallee(_callee);
}
/**
* @dev updates the internal configuration of the controller
*/
function _refreshConfigInternal() internal {
whitelist = WhitelistInterface(addressbook.getWhitelist());
oracle = OracleInterface(addressbook.getOracle());
calculator = MarginCalculatorInterface(addressbook.getMarginCalculator());
pool = MarginPoolInterface(addressbook.getMarginPool());
}
}
|
return if an expired oToken contract’s settlement price has been finalized _otoken address of the oToken return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not/
|
function isSettlementAllowed(address _otoken) public view returns (bool) {
OtokenInterface otoken = OtokenInterface(_otoken);
address underlying = otoken.underlyingAsset();
address strike = otoken.strikeAsset();
address collateral = otoken.collateralAsset();
uint256 expiry = otoken.expiryTimestamp();
bool isUnderlyingFinalized = oracle.isDisputePeriodOver(underlying, expiry);
bool isStrikeFinalized = oracle.isDisputePeriodOver(strike, expiry);
bool isCollateralFinalized = oracle.isDisputePeriodOver(collateral, expiry);
return isUnderlyingFinalized && isStrikeFinalized && isCollateralFinalized;
}
| 942,802
|
pragma solidity ^0.4.24;
/*
* CrystalAirdropGame
* Author: InspiGames
* Website: https://cryptominingwar.github.io/
*/
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;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract CryptoMiningWarInterface {
uint256 public roundNumber;
uint256 public deadline;
function addCrystal( address _addr, uint256 _value ) public {}
}
contract CrystalAirdropGame {
using SafeMath for uint256;
address public administrator;
// mini game
uint256 public MINI_GAME_TIME_DEFAULT = 60 * 5;
uint256 public MINI_GAME_PRIZE_CRYSTAL = 100;
uint256 public MINI_GAME_BETWEEN_TIME = 8 hours;
uint256 public MINI_GAME_ADD_TIME_DEFAULT = 15;
address public miningWarContractAddress;
uint256 public miniGameId = 0;
uint256 public noRoundMiniGame;
CryptoMiningWarInterface public MiningWarContract;
/**
* Admin can set the bonus of game's reward
*/
uint256 public MINI_GAME_BONUS = 100;
/**
* @dev mini game information
*/
mapping(uint256 => MiniGame) public minigames;
/**
* @dev player information
*/
mapping(address => PlayerData) public players;
struct MiniGame {
uint256 miningWarRoundNumber;
bool ended;
uint256 prizeCrystal;
uint256 startTime;
uint256 endTime;
address playerWin;
uint256 totalPlayer;
}
struct PlayerData {
uint256 currentMiniGameId;
uint256 lastMiniGameId;
uint256 win;
uint256 share;
uint256 totalJoin;
uint256 miningWarRoundNumber;
}
event eventEndMiniGame(
address playerWin,
uint256 crystalBonus
);
event eventJoinMiniGame(
uint256 totalJoin
);
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
constructor() public {
administrator = msg.sender;
// set interface main contract
miningWarContractAddress = address(0xf84c61bb982041c030b8580d1634f00fffb89059);
MiningWarContract = CryptoMiningWarInterface(miningWarContractAddress);
}
/**
* @dev MainContract used this function to verify game's contract
*/
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
/**
* @dev set discount bonus for game
* require is administrator
*/
function setDiscountBonus( uint256 _discountBonus ) public
{
require( administrator == msg.sender );
MINI_GAME_BONUS = _discountBonus;
}
/**
* @dev Main Contract call this function to setup mini game.
* @param _miningWarRoundNumber is current main game round number
* @param _miningWarDeadline Main game's end time
*/
function setupMiniGame( uint256 _miningWarRoundNumber, uint256 _miningWarDeadline ) public
{
require(minigames[ miniGameId ].miningWarRoundNumber < _miningWarRoundNumber && msg.sender == miningWarContractAddress);
// rerest current mini game to default
minigames[ miniGameId ] = MiniGame(0, true, 0, 0, 0, 0x0, 0);
noRoundMiniGame = 0;
startMiniGame();
}
/**
* @dev start the mini game
*/
function startMiniGame() private
{
uint256 miningWarRoundNumber = getMiningWarRoundNumber();
require(minigames[ miniGameId ].ended == true);
// caculate information for next mini game
uint256 currentPrizeCrystal;
if ( noRoundMiniGame == 0 ) {
currentPrizeCrystal = SafeMath.div(SafeMath.mul(MINI_GAME_PRIZE_CRYSTAL, MINI_GAME_BONUS),100);
} else {
uint256 rate = 168 * MINI_GAME_BONUS;
currentPrizeCrystal = SafeMath.div(SafeMath.mul(minigames[miniGameId].prizeCrystal, rate), 10000); // price * 168 / 100 * MINI_GAME_BONUS / 100
}
uint256 startTime = now + MINI_GAME_BETWEEN_TIME;
uint256 endTime = startTime + MINI_GAME_TIME_DEFAULT;
noRoundMiniGame = noRoundMiniGame + 1;
// start new round mini game
miniGameId = miniGameId + 1;
minigames[ miniGameId ] = MiniGame(miningWarRoundNumber, false, currentPrizeCrystal, startTime, endTime, 0x0, 0);
}
/**
* @dev end Mini Game's round
*/
function endMiniGame() private
{
require(minigames[ miniGameId ].ended == false && (minigames[ miniGameId ].endTime <= now ));
uint256 crystalBonus = SafeMath.div( SafeMath.mul(minigames[ miniGameId ].prizeCrystal, 50), 100 );
// update crystal bonus for player win
if (minigames[ miniGameId ].playerWin != 0x0) {
PlayerData storage p = players[minigames[ miniGameId ].playerWin];
p.win = p.win + crystalBonus;
}
// end current mini game
minigames[ miniGameId ].ended = true;
emit eventEndMiniGame(minigames[ miniGameId ].playerWin, crystalBonus);
// start new mini game
startMiniGame();
}
/**
* @dev player join this round
*/
function joinMiniGame() public disableContract
{
require(now >= minigames[ miniGameId ].startTime && minigames[ miniGameId ].ended == false);
PlayerData storage p = players[msg.sender];
if (now <= minigames[ miniGameId ].endTime) {
// update player data in current mini game
if (p.currentMiniGameId == miniGameId) {
p.totalJoin = p.totalJoin + 1;
} else {
// if player join an new mini game then update share of last mini game for this player
updateShareCrystal();
p.currentMiniGameId = miniGameId;
p.totalJoin = 1;
p.miningWarRoundNumber = minigames[ miniGameId ].miningWarRoundNumber;
}
// update information for current mini game
if ( p.totalJoin <= 1 ) { // this player into the current mini game for the first time
minigames[ miniGameId ].totalPlayer = minigames[ miniGameId ].totalPlayer + 1;
}
minigames[ miniGameId ].playerWin = msg.sender;
minigames[ miniGameId ].endTime = minigames[ miniGameId ].endTime + MINI_GAME_ADD_TIME_DEFAULT;
emit eventJoinMiniGame(p.totalJoin);
} else {
// need run end round
if (minigames[ miniGameId ].playerWin == 0x0) {
updateShareCrystal();
p.currentMiniGameId = miniGameId;
p.lastMiniGameId = miniGameId;
p.totalJoin = 1;
p.miningWarRoundNumber = minigames[ miniGameId ].miningWarRoundNumber;
minigames[ miniGameId ].playerWin = msg.sender;
}
endMiniGame();
}
}
/**
* @dev update share bonus for player who join the game
*/
function updateShareCrystal() private
{
uint256 miningWarRoundNumber = getMiningWarRoundNumber();
PlayerData storage p = players[msg.sender];
// check current mini game of player join. if mining war start new round then reset player data
if ( p.miningWarRoundNumber != miningWarRoundNumber) {
p.share = 0;
p.win = 0;
} else if (minigames[ p.currentMiniGameId ].ended == true && p.lastMiniGameId < p.currentMiniGameId && minigames[ p.currentMiniGameId ].miningWarRoundNumber == miningWarRoundNumber) {
// check current mini game of player join, last update mini game and current mining war round id
// require this mini game is children of mining war game( is current mining war round id )
p.share = SafeMath.add(p.share, calculateShareCrystal(p.currentMiniGameId));
p.lastMiniGameId = p.currentMiniGameId;
}
}
/**
* @dev claim crystals
*/
function claimCrystal() public
{
// should run end round
if ( minigames[miniGameId].endTime < now ) {
endMiniGame();
}
updateShareCrystal();
// update crystal for this player to main game
uint256 crystalBonus = players[msg.sender].win + players[msg.sender].share;
MiningWarContract.addCrystal(msg.sender,crystalBonus);
// update player data. reset value win and share of player
PlayerData storage p = players[msg.sender];
p.win = 0;
p.share = 0;
}
/**
* @dev calculate share crystal of player
*/
function calculateShareCrystal(uint256 _miniGameId) public view returns(uint256 _share)
{
PlayerData memory p = players[msg.sender];
if ( p.lastMiniGameId >= p.currentMiniGameId && p.currentMiniGameId != 0) {
_share = 0;
} else {
_share = SafeMath.div( SafeMath.div( SafeMath.mul(minigames[ _miniGameId ].prizeCrystal, 50), 100 ), minigames[ _miniGameId ].totalPlayer );
}
}
function getMiningWarDealine () private view returns( uint256 _dealine )
{
_dealine = MiningWarContract.deadline();
}
function getMiningWarRoundNumber () private view returns( uint256 _roundNumber )
{
_roundNumber = MiningWarContract.roundNumber();
}
}
|
set discount bonus for game require is administrator/
|
function setDiscountBonus( uint256 _discountBonus ) public
{
require( administrator == msg.sender );
MINI_GAME_BONUS = _discountBonus;
}
| 2,124,684
|
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, 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.8.7;
library AddressAliasHelper {
uint160 constant offset = uint160(0x1111000000000000000000000000000000001111);
/// @notice Utility function that converts the address in the L1 that submitted a tx to
/// the inbox to the msg.sender viewed in the L2
/// @param l1Address the address in the L1 that triggered the tx to L2
/// @return l2Address L2 address as viewed in msg.sender
function applyL1ToL2Alias(address l1Address)
internal
pure
returns (address l2Address)
{
unchecked {
l2Address = address(uint160(l1Address) + offset);
}
}
/// @notice Utility function that converts the msg.sender viewed in the L2 to the
/// address in the L1 that submitted a tx to the inbox
/// @param l2Address L2 address as viewed in msg.sender
/// @return l1Address the address in the L1 that triggered the tx to L2
function undoL1ToL2Alias(address l2Address)
internal
pure
returns (address l1Address)
{
unchecked {
l1Address = address(uint160(l2Address) - offset);
}
}
}
|
Utility function that converts the msg.sender viewed in the L2 to the address in the L1 that submitted a tx to the inbox l2Address L2 address as viewed in msg.sender return l1Address the address in the L1 that triggered the tx to L2
|
function undoL1ToL2Alias(address l2Address)
internal
pure
returns (address l1Address)
{
unchecked {
l1Address = address(uint160(l2Address) - offset);
}
}
| 996,914
|
./full_match/73799/0xD3c6b3180B96270FF6497468333Bc485e9EE0a96/sources/contracts/libraries/LibAdmin.sol
|
- setAdminFunction - sets the function selector as an admin function or not functionSelector signature of the function isAllowed boolean flag indicating whether the function selector is an admin function or not - only the admin can set the function selector as an admin function or not/
|
function setAdminFunction(bytes4 functionSelector, bool isAllowed) internal {
LibClaimManager.checkOwnership();
if (getStorage().isAdminFunction[functionSelector] == isAllowed) {
revert ProxyError("Admin function already set");
}
| 16,362,955
|
// 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 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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 (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/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.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);
}
// 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/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITerraformsData {
function tokenURI(uint, uint, uint, uint, uint, uint[] memory)
external
view
returns (string memory);
function tokenHTML(uint, uint, uint, uint, uint[] memory)
external
view
returns (string memory);
function tokenSVG(uint, uint, uint, uint, uint[] memory)
external
view
returns (string memory);
function tokenTerrain(uint, uint, uint)
external
view
returns (int[32][32] memory);
function tokenCharacters(uint, uint, uint, uint, uint[] memory)
external
view
returns (string[32][32] memory);
function tokenHeightmapIndices(uint, uint, uint, uint, uint[] memory)
external
view
returns (uint[32][32] memory);
function tokenZone(uint, uint)
external
view
returns (string[10] memory, string memory);
function characterSet(uint, uint)
external
view
returns (string[9] memory, uint, uint, uint);
function levelAndTile(uint, uint) external view returns (uint, uint);
function tileOrigin(uint, uint, uint, uint, uint)
external
view
returns (int, int, int);
function levelDimensions(uint) external view returns (uint);
function tokenElevation(uint, uint, uint) external view returns (int);
function prerevealURI(uint) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/* TERRAFORMS
. . # # - _ _ > _ _ - - # # # # . + + ^ + . . # - _ } ~
. . # - - _ > } } _ _ _ - - - - # . + + + + . # - _ ~ ~
# # # - _ _ } ~ ~ ~ } > _ _ _ - # . + ^ ^ + . # - _ } ~
# - - - _ > } ~ ~ ~ ~ ~ ~ ~ } _ - . + ^ ^ ^ + . # - > ~
- - _ _ _ > ~ ~ ~ ~ ~ ~ ~ ~ ~ _ - . + ^ ^ ^ ^ + . - _ }
_ _ _ _ _ > } ~ ~ ~ ~ ~ ~ ~ ~ _ # . ^ ^ ^ ^ ^ + . # - _
_ > > _ _ _ _ } ~ ~ ~ ~ ~ ~ > - # + ^ ^ ^ ^ ^ + . # - -
_ > _ _ - - - _ } ~ ~ ~ } _ _ # . ^ ^ ^ ^ ^ ^ + . # # -
_ _ _ - - # # - _ _ > > _ - # . ^ ^ ^ ^ ^ ^ + . # # # #
_ _ - # # . # # - - _ _ - # . + ^ ^ ^ ^ ^ + . # # - - #
- - # # . . . . # - - - # . . ^ ^ ^ ^ ^ ^ . # - - - - #
# # # . + ^ + + . # # # . . + ^ ^ ^ ^ ^ + . # - _ _ - -
# # . + ^ ^ ^ ^ + . . . . + ^ ^ ^ ^ ^ ^ . # - - _ _ - #
# . . ^ ^ ^ ^ ^ ^ ^ + + + ^ ^ ^ ^ ^ ^ + . # - - - - - #
- . . ^ ^ ^ ^ ^ ^ ^ ^ + + ^ ^ ^ ^ + + . # # # - - # # #
- # . + ^ ^ ^ ^ ^ ^ ^ ^ + + + + . . # # # # # # # . . .
_ - # . + ^ ^ ^ ^ ^ ^ ^ + . . # # - - - # # . . . + + +
> - # . + ^ ^ ^ ^ ^ ^ + . . # - _ _ _ _ - # . . + ^ ^ +
} _ - # . + ^ ^ ^ ^ ^ + . # - _ > } } _ - # . . + ^ ^ +
} _ - # . + ^ ^ ^ ^ ^ + . # - _ } ~ ~ } _ - # . + + ^ +
} _ - # . + ^ ^ ^ ^ ^ + . # - _ } ~ ~ ~ } _ - # . + + +
> _ - # . + ^ ^ ^ ^ ^ + . # - _ } ~ ~ ~ ~ _ - - # . + +
_ _ - # . + ^ ^ ^ ^ ^ + . . # - > ~ ~ ~ ~ > _ - # . + +
- - - # # . + ^ ^ ^ ^ ^ + . # - _ } ~ ~ } _ - - # . + ^
- - # # # . . + ^ ^ ^ ^ ^ + . # - _ > } _ _ - # . + ^ ^
# # # # # # # . + ^ ^ ^ ^ ^ + . # - _ _ _ - # . . + ^ ^
. . # # - - - # . + + ^ ^ ^ + . # # - - - # # . + ^ ^ ^
+ . # # - - - - # . . + + + + . . # - - - # . + + ^ ^ ^
*/
import "./ITerraformsData.sol";
import "./TerraformsPlacements.sol";
/// @title Land parcels in an onchain 3D megastructure
/// @author xaltgeist, with code direction and consultation from 0x113d
contract Terraforms is TerraformsPlacements {
/// @notice Tokens are pieces of an onchain 3D megastructure. Represents a
/// level of the structure
struct StructureLevel {
uint levelNumber;
uint tokensOnLevel;
int structureSpaceX;
int structureSpaceY;
int structureSpaceZ;
}
/// @notice Supplemental token data, including spatial information
struct TokenData {
uint tokenId;
uint level;
uint xCoordinate;
uint yCoordinate;
int elevation;
int structureSpaceX;
int structureSpaceY;
int structureSpaceZ;
string zoneName;
string[10] zoneColors;
string[9] characterSet;
}
/// @notice Address of contract managing augmentations
address public immutable terraformsAugmentationsAddress;
/// @notice This constant is the length of a token in 3D space
int public constant TOKEN_SCALE = 6619 * 32;
/// @notice An append-only list of optional (opt-in) tokenURI upgrades
address[] public tokenURIAddresses;
// The array index of the tokenURIAddress for each token
mapping(uint => uint) tokenToURIAddressIndex;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* CONSTRUCTOR, FALLBACKS
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
constructor(
address _terraformsDataAddress,
address _terraformsAugmentationsAddress
)
ERC721("Terraforms", "TERRAFORMS")
Ownable()
{
tokenURIAddresses.push(_terraformsDataAddress);
terraformsAugmentationsAddress = _terraformsAugmentationsAddress;
}
receive() external payable {}
fallback() external payable {}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* FUNCTION MODIFIERS
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
modifier publicMint (uint numTokens) {
require(numTokens <= 10, "Max 10");
require(
tokenCounter <= (SUPPLY - numTokens) &&
msg.value >= numTokens * PRICE
);
_;
}
modifier postReveal (uint tokenId) {
require(seed != 0 && _exists(tokenId));
_;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* PUBLIC: MINTING
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/// @notice Mint tokens
/// @param numTokens The amount of tokens
function mint(uint numTokens)
public
payable
nonReentrant
publicMint(numTokens)
{
require(!mintingPaused, "Paused");
_mintTokens(msg.sender, numTokens);
}
/// @notice Mints tokens if you hold Loot or a mintpass
/// @dev Queries the Loot contract to check if minter is a holder
/// @param numTokens The amount of tokens
function earlyMint(uint numTokens)
public
payable
nonReentrant
publicMint(numTokens)
{
require(earlyMintActive, "Inactive");
require(
balanceOf(msg.sender) <= 100 && // Early wallet limit of 100
(
IERC721(
0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7
).balanceOf(msg.sender) > 0 || // Check if sender has Loot
addressToMintpass[msg.sender] != Mintpass.None // Or a mintpass
)
);
_mintTokens(msg.sender, numTokens);
}
/// @notice Redeems a mintpass for a dreaming token
function redeemMintpass() public nonReentrant {
require(addressToMintpass[msg.sender] == Mintpass.Unused);
addressToMintpass[msg.sender] = Mintpass.Used;
_mintTokens(msg.sender, 1);
dreamers += 1;
tokenToDreamBlock[tokenCounter] = block.number;
tokenToStatus[tokenCounter] = Status.OriginDaydream;
emit Daydreaming(tokenCounter);
}
/// @notice Allows owners to claim an allotment of tokens
/// @param to The recipient address
/// @param numTokens The amount of tokens
function ownerClaim(address to, uint numTokens) public onlyOwner {
require(
tokenCounter >= SUPPLY &&
tokenCounter <= (MAX_SUPPLY - numTokens)
);
_mintTokens(to, numTokens);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* PUBLIC: TOKEN DATA
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/// @notice Returns the token URI
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
/// @dev Token owners can specify which tokenURI address to use
/// on a per-token basis using setTokenURIAddress
/// @return result A base64 encoded JSON string
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory result)
{
if (seed == 0){ // If tokens aren't revealed yet, return a placeholder
result = ITerraformsData(tokenURIAddresses[0]).prerevealURI(tokenId);
} else { // Otherwise, call the token's specified tokenURI address
result = ITerraformsData(
tokenURIAddresses[tokenToURIAddressIndex[tokenId]]
).tokenURI(
tokenId,
uint(tokenToStatus[tokenId]),
tokenToPlacement[tokenId],
seed,
_yearsOfDecay(block.timestamp),
tokenToCanvasData[tokenId]
);
}
}
/// @notice Returns HTML containing the token SVG
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
/// @return result A plaintext HTML string with a plaintext token SVG
function tokenHTML(uint tokenId)
public
view
postReveal(tokenId)
returns (string memory result)
{
result = ITerraformsData( // Call the token's specified tokenURI address
tokenURIAddresses[tokenToURIAddressIndex[tokenId]]
).tokenHTML(
uint(tokenToStatus[tokenId]),
tokenToPlacement[tokenId],
seed,
_yearsOfDecay(block.timestamp),
tokenToCanvasData[tokenId]
);
}
/// @notice Returns an SVG of the token
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
/// @return A plaintext SVG
function tokenSVG(uint tokenId)
public
view
postReveal(tokenId)
returns (string memory)
{
return ITerraformsData( // Call the token's specified tokenURI address
tokenURIAddresses[tokenToURIAddressIndex[tokenId]]
).tokenSVG(
uint(tokenToStatus[tokenId]),
tokenToPlacement[tokenId],
seed,
_yearsOfDecay(block.timestamp),
tokenToCanvasData[tokenId]
);
}
/// @notice Returns the characters composing the token image
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
/// @return A 2D array of strings
function tokenCharacters(uint tokenId)
public
view
postReveal(tokenId)
returns (string[32][32] memory)
{
return ITerraformsData( // Call the token's specified tokenURI address
tokenURIAddresses[tokenToURIAddressIndex[tokenId]]
).tokenCharacters(
uint(tokenToStatus[tokenId]),
tokenToPlacement[tokenId],
seed,
_yearsOfDecay(block.timestamp),
tokenToCanvasData[tokenId]
);
}
/// @notice Returns the integer values that determine the token's topography
/// @dev Values are 16-bit signed ints (i.e., +/- 65536)
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
/// @return A 2D array of signed integers
function tokenTerrainValues(uint tokenId)
public
view
postReveal(tokenId)
returns (int[32][32] memory)
{
return ITerraformsData( // Call the token's specified tokenURI address
tokenURIAddresses[tokenToURIAddressIndex[tokenId]]
).tokenTerrain(
tokenToPlacement[tokenId],
seed,
_yearsOfDecay(block.timestamp)
);
}
/// @notice Returns the stepwise height values visually represented on token
/// @dev Values range from 0 (highest) to 8 (lowest). 9 indicates empty
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
/// @return A 2D array of unsigned integers
function tokenHeightmapIndices(uint tokenId)
public
view
postReveal(tokenId)
returns (uint[32][32] memory)
{
return ITerraformsData( // Call the token's specified tokenURI address
tokenURIAddresses[tokenToURIAddressIndex[tokenId]]
).tokenHeightmapIndices(
uint(tokenToStatus[tokenId]),
tokenToPlacement[tokenId],
seed,
_yearsOfDecay(block.timestamp),
tokenToCanvasData[tokenId]
);
}
/// @notice Spatial information about the token structure at a given time
/// @dev Spatial values used to generate visuals are offset by
/// (seed * TOKEN_SCALE). Return values remove that offset
/// @param timestamp The point in time to visualize the structure
/// @return structure An array of StructureLevel structs
function structureData(uint timestamp)
public
view
returns (StructureLevel[20] memory structure)
{
ITerraformsData terraformsData = ITerraformsData(tokenURIAddresses[0]);
uint decay = _yearsOfDecay(timestamp);
// Structure is offset into 3D space by the seed * the size of a tile
// That offset is removed for ease of use
int xyzNormalization = int(seed) * TOKEN_SCALE;
// Temporary variables for loop
int x;
int y;
int z;
for (uint i; i < 20; i++){
// Get XYZ origin for 0,0 tile on each level
(x, y, z) = terraformsData.tileOrigin(i, 0, seed, decay, timestamp);
// Add level to result array
structure[i] = StructureLevel(
i + 1, // Adjust level from zero-index
terraformsData.levelDimensions(i) ** 2, // n Tokens == edge^2
x - xyzNormalization,
y - xyzNormalization,
z - xyzNormalization
);
}
return structure;
}
/// @notice Data re: a token's visual composition and location on structure
/// @dev Spatial values used to generate visuals are offset by
/// (seed * TOKEN_SCALE). Return values remove that offset
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
/// @return result A TokenData struct
function tokenSupplementalData(uint tokenId)
public
view
postReveal(tokenId)
returns (TokenData memory result)
{
ITerraformsData terraformsData = ITerraformsData(
tokenURIAddresses[tokenToURIAddressIndex[tokenId]]
);
// Structure is offset into 3D space by the seed * the size of a tile
// That offset is removed for ease of use
int xyzNormalization = int(seed) * TOKEN_SCALE;
(uint level, uint tile) = terraformsData.levelAndTile(
tokenToPlacement[tokenId],
seed
);
uint dimensions = terraformsData.levelDimensions(level);
result.elevation = terraformsData.tokenElevation(level, tile, seed);
(
result.structureSpaceX,
result.structureSpaceY,
result.structureSpaceZ
) = terraformsData.tileOrigin(
level,
tile,
seed,
_yearsOfDecay(block.timestamp),
block.timestamp
);
(result.zoneColors, result.zoneName) = terraformsData.tokenZone(
tokenToPlacement[tokenId],
seed
);
(result.characterSet, , , ) = terraformsData.characterSet(
tokenToPlacement[tokenId], seed
);
result.level = level + 1; // Adjust from zero-index
result.xCoordinate = tile % dimensions;
result.yCoordinate = tile / dimensions;
result.structureSpaceX -= xyzNormalization;
result.structureSpaceY -= xyzNormalization;
result.structureSpaceZ -= xyzNormalization;
return result;
}
/// @notice Token owner can set tokenURI address for an array of tokens
/// @param tokens The tokens to set to the new URI address
/// @param index The index of the new tokenURIAddress in tokenURIAddresses
function setTokenURIAddress(uint[] memory tokens, uint index) public {
require(index < tokenURIAddresses.length);
for(uint i; i < tokens.length; i++){
require(msg.sender == ownerOf(tokens[i]));
tokenToURIAddressIndex[tokens[i]] = index;
}
}
/// @notice Owner can add new opt-in tokenURI address
/// @param newAddress The new tokenURI address
function addTokenURIAddress(address newAddress) public onlyOwner {
tokenURIAddresses.push(newAddress);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* INTERNAL: MINTING
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/// @notice Internal function for minting tokens
/// @param to The recipient address
/// @param numTokens The amount of tokens
function _mintTokens(address to, uint numTokens) internal {
uint base = tokenCounter;
while (tokenCounter < base + numTokens) {
_shufflePlacements();
tokenCounter += 1;
_safeMint(to, tokenCounter);
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* INTERNAL: TOKEN DATA
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/// @notice Returns the amount of decay to apply to the token structure
/// @dev Decay begins unless there are enough dreamers
/// @param timestamp The point in time for determining decay
/// @return The years of decay affecting the tokens
function _yearsOfDecay(uint timestamp) internal view returns (uint) {
uint decayBegins = REVEAL_TIMESTAMP + dreamers * 3_650 days;
if (dreamers >= 500 || timestamp <= decayBegins) {
return 0;
} else {
return (timestamp - decayBegins) / 365 days;
}
}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* LICENSES
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
FOR UPDATES AND ADDITIONAL INFO ABOUT THE LICENSE RELATING TO THIS PROJECT,
SEE WWW.MATHCASTLES.XYZ
AS OF DEPLOY TIME, THE FOLLOWING LICENSE APPLIES TO THIS PROJECT'S ARTWORK
(EXCLUDING ITS FONTS, WHICH ARE COVERED BY THE LICENSE BELOW THIS LICENSE):
# License - Terraforms by Mathcastles
## 1. Purpose
This license (this “**License**”) was created by Mathcastles LLC
("**Mathcastles**") to promote the interests of and to foster the innovations
and creativity of NFT collectors and developers. This License seeks to maximize
the rights of owners to enjoy and profit from the NFTs they own while preserving
their value for future owners.
## 2. Summary
### 2.A. Owners of Terraforms NFTs can:
1. Display, reproduce and commercialize the Art (defined below) while they own
the NFTs, with optional attribution.
2. Develop and commercialize derivative works of the Art, both physical and
virtual (including, for example, fractionalizations) while they own the
corresponding NFTs, with optional attribution.
3. Continue to commercialize derivative works of the Art of NFTs they previously
owned if the derivative works were developed and released while they owned the
NFTs.
4. Use the Art for personal, non-commercial use.
5. Display the Art on marketplaces for buying and selling their NFTs.
6. Use their NFTs to interact with websites and apps, including decentralized
apps (dapps).
### 2.B. Owners of Terraforms NFTs cannot:
1. Transfer the rights granted by this license to anyone, or to the public.
2. Commercialize the Art of NFTs they do not currently own, or develop or
release derivative works of the Art of NFTs they do not currently own.
3. Register or attempt to enforce any intellectual property rights in any
derivative work of the Art, in a manner that would limit a past, present or
future owner from commercializing the Art or creating derivative works in
accordance with this license.
### 2.C. Additional Terms for Commercial Enterprises:
If an owner, together with its direct and indirect affiliates, operates an
enterprise that has ten (10) or more employees or US$5,000,000 or more per year
in gross receipts, then the owner cannot make more than US$500,000 in total
annual revenue from commercializing its NFTs or derivatives without separate
written permission from Mathcastles.
## 3. Terms
### 3.A. Definitions
“**Art**” means any art, design, and related underlying data that may be
associated with an NFT that you Own.
"**Commercial Enterprise**" means any natural person, incorporated entity, or
other commercial venture, together with its direct and indirect owners and
affiliates, which during any of the last three calendar years had, in the
aggregate, (i) ten (10) or more employees or (ii) the equivalent of
US$5,000,000 or more per year in gross receipts.
"**Creator**" means Mathcastles LLC.
“**Derivatives**” means extensions or derivative works created by you of
Purchased NFTs that include, or contain or are derived from the Art.
"**NFT**" means an Ethereum blockchain-tracked non-fungible token created from
this contract.
“**Own**” means, with respect to an NFT, an NFT that you have purchased or
otherwise rightfully acquired, where proof of such purchase is recorded on the
relevant blockchain, and that you continue to possess.
“**Purchased NFT**” means an NFT that you Own.
“**Third Party IP**” means any third party patent rights (including, without
limitation, patent applications and disclosures), copyrights, trade secrets,
trademarks, know-how or any other intellectual property rights recognized in any
country or jurisdiction in the world.
### 3.B. Ownership
You acknowledge and agree that Creator (or, as applicable, its licensors) owns
all legal right, title and interest in and to the Art, and all intellectual
property rights therein. The rights that you have in and to the Art are limited
to those described in this License. Creator reserves all rights in and to the
Art not expressly granted to you in this License.
### 3.C. License
#### 3.C.1. General Use
Subject to your continued compliance with the terms of this License, Creator
grants you a worldwide, non-exclusive, non-transferable, royalty-free license to
use, copy, and display the Art for your Purchased NFTs, along with any
Derivatives that you choose to create or use, solely for the following purposes:
1. for your own personal, non-commercial use;
2. as part of a marketplace that permits the purchase and sale of your NFTs; or
3. as part of a third party website or application that permits the inclusion,
involvement, or participation of your NFTs.
#### 3.C.2. Commercial and Derivative Use
Creator grants you a limited, worldwide, non-exclusive, non-transferable license
to use, copy, and display the Art for your Purchased NFTs for the purpose of
commercializing your own physical or virtual merchandise that includes,
contains, or consists of the Art for your Purchased NFTs (“**Commercial Use**”)
and to commercialize Derivatives of your Purchased NFTs ("**Derivative Use**"),
provided that if you are a Commercial Enterprise, such Commercial Use and
Derivative Use do not in the aggregate result in you earning more than Five
Hundred Thousand U.S. Dollars (US$500,000) in gross revenue in any year. For
the sake of clarity, nothing in this Section 3.C.2. will be deemed to restrict
you from:
1. owning or operating a marketplace that permits the use and sale of NFTs
generally;
2. owning or operating a third party website or application that permits the
inclusion, involvement, or participation of NFTs generally; or
3. earning revenue from any of the foregoing, even where such revenue is in
excess of US$500,000 per year.
### 3.D. Restrictions
#### 3.D.1. No Additional IP Rights
You may not attempt to trademark, copyright, or otherwise acquire additional
intellectual property rights in the Art, nor permit any third party to do or
attempt to do any of the foregoing, without Creator’s express prior written
consent; _provided_, that this section does not prohibit an owner from acquiring
intellectual property rights in a derivative work.
#### 3.D.2. No License Granted as to Third Party IP
To the extent that Art associated with your Purchased NFTs contains Third Party
IP (for example, licensed intellectual property from a third party artist,
company, or public figure), you understand and agree as follows:
1. that the inclusion of any Third Party IP in the Art does not grant you any
rights to use such Third Party IP except as it is incorporated in the Art;
2. that, depending on the nature of the license granted from the owner of the
Third Party IP, Creator may need to pass through additional restrictions on your
ability to use the Art; and
3. to the extent that Creator informs you of such additional restrictions in
writing (including by email), you will be responsible for complying with all
such restrictions from the date that you receive the notice, and that failure
to do so will be deemed a breach of this license.
The restrictions in this Section 3.D. will survive the expiration or termination
of this License.
### 3.E. Limitations of License
Except for the right to Derivative Use described in Section 3.C.2., the license
granted in this Section 3 applies only to the extent that you continue to Own
the applicable Purchased NFT. If at any time you sell, trade, donate, give away,
transfer, or otherwise dispose of your Purchased NFT for any reason, the license
granted in Section 3 (except for the right to Derivative Use described in
Section 3.C.2.) will immediately expire with respect to those NFTs without the
requirement of notice, and you will have no further rights in or to the Art for
those NFTs. The right to Derivative Use described in Section 3.C.2. shall
continue indefinitely for so long as you comply with this License.
If you are a Commercial Enterprise and you exceed the US$500,000 limitation on
annual gross revenue set forth in Section 3.C.2. above, you will be in breach of
this License, and must send an email to Creator at license@mathcastles.xyz
within fifteen (15) days, with the phrase “NFT License - Commercial Use” in the
subject line, requesting a discussion with Creator regarding entering into a
broader license agreement or obtaining an exemption (which may be granted or
withheld in Creator’s sole and absolute discretion).
If you exceed the scope of the license grant in this Section 3 without entering
into a broader license agreement with or obtaining an exemption from Creator,
you acknowledge and agree that:
1. you are in breach of this License;
2. in addition to any remedies that may be available to Creator at law or in
equity, the Creator may immediately terminate this License, without the
requirement of notice; and
3. you will be responsible to reimburse Creator for any costs and expenses
incurred by Creator during the course of enforcing the terms of this License
against you.
********************************************************************************
THE FOLLOWING LICENSE APPLIES TO THE FONTS USED IN THIS PROJECT
Copyright 2018 The Noto Project Authors (github.com/googlei18n/noto-fonts)
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to
provide a free and open framework in which fonts may be shared and
improved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software
components as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to,
deleting, or substituting -- in part or in whole -- any of the
components of the Original Version, by changing formats or by porting
the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed,
modify, redistribute, and sell modified and unmodified copies of the
Font Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created using
the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/// @title Admin functions and access control for the Terraforms contract
/// @author xaltgeist
abstract contract TerraformsAdmin is ERC721Enumerable, ReentrancyGuard, Ownable{
enum Mintpass {None, Unused, Used}
/// @notice Sale information
uint public constant PRICE = 0.16 ether;
uint public constant MAX_SUPPLY = 11_104;
uint public constant OWNER_ALLOTMENT = 1_200;
uint public constant SUPPLY = MAX_SUPPLY - OWNER_ALLOTMENT;
uint public tokenCounter;
bool public earlyMintActive;
bool public mintingPaused = true;
mapping(address => Mintpass) addressToMintpass;
/// @notice Toggles whether claimers can mint (other than through early)
function togglePause() public onlyOwner {
mintingPaused = !mintingPaused;
}
/// @notice Toggles whether Loot and mintpass holders can mint early
function toggleEarly() public onlyOwner {
earlyMintActive = !earlyMintActive;
}
/// @notice Sets the addresses of mintpass holders
function setMintpassHolders(address[] memory mintpassHolders)
public
onlyOwner
{
for (uint i; i < mintpassHolders.length; i ++){
addressToMintpass[mintpassHolders[i]] = Mintpass.Unused;
}
}
/// @notice Transfers the contract balance to the owner
function withdraw() public onlyOwner {
(bool success, ) = owner().call{value: address(this).balance}("");
require(success);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./TerraformsAdmin.sol";
/// @author xaltgeist
/// @title Tokens can be transformed to painter apps or terraformed
abstract contract TerraformsDreaming is TerraformsAdmin {
/// Tokens can have one of five statuses:
/// 0. Terrain: The default visual presentation
/// 1. Daydream: A blank token that users can paint on
/// 2. Terraformed: A terraformed token with user-supplied visuals
/// 3. OriginDaydream: A daydream token that was dreaming on mint
/// 4. OriginTerraformed: A terraformed OriginDaydream token
enum Status {
Terrain,
Daydream,
Terraformed,
OriginDaydream,
OriginTerraformed
}
uint public dreamers; // Number of dreaming tokens
mapping(uint => uint) public tokenToDreamBlock;
mapping(uint => Status) public tokenToStatus;
mapping(uint => uint[]) public tokenToCanvasData;
mapping(uint => address) public tokenToDreamer;
mapping(uint => address) public tokenToAuthorizedDreamer;
event Daydreaming(uint tokenId);
event Terraformed(uint tokenId, address terraformer);
/// @notice *PERMANENTLY* sets a token to dreaming, changing its attributes
/// @dev A minimum amount must be dreaming to prevent collapse
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
function enterDream(uint tokenId) public {
require(msg.sender == ownerOf(tokenId));
tokenToDreamBlock[tokenId] = block.number;
if (tokenToStatus[tokenId] == Status.Terrain){
dreamers += 1;
}
if (uint(tokenToStatus[tokenId]) > 2){
tokenToStatus[tokenId] = Status.OriginDaydream;
} else {
tokenToStatus[tokenId] = Status.Daydream;
}
emit Daydreaming(tokenId);
}
/// @notice Authorizes an address to commit canvas data to a dreaming token
/// @dev To revoke, call authorizeDreamer with address(0).
/// NOTE Authorization is automatically revoked on transfer.
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
/// @param authorizedDreamer The address authorized to commit canvas data
function authorizeDreamer(uint tokenId, address authorizedDreamer) public {
require(msg.sender == ownerOf(tokenId));
tokenToAuthorizedDreamer[tokenId] = authorizedDreamer;
}
/// @notice Sets a dreaming token's canvas to a user-supplied drawing
/// @dev The drawing data is encoded as 16 uints. The 64 least significant
/// digits of each uint represent values from 0-9 at successive x,y
/// positions on the token, beginning in the top left corner. Each
/// value will be obtained from left to right by taking the current
/// uint mod 10, and then advancing to the next digit until all uints
/// are exhausted.
/// @param tokenId The tokenId, from 1 to tokenCounter (max MAX_SUPPLY)
/// @param dream An array of 16 uints, each representing the heightmap
/// indices of two rows
function commitDreamToCanvas(uint tokenId, uint[16] memory dream) public {
require(
(
msg.sender == ownerOf(tokenId) ||
msg.sender == tokenToAuthorizedDreamer[tokenId]
) &&
uint(tokenToStatus[tokenId]) % 2 == 1
);
tokenToDreamer[tokenId] = msg.sender;
tokenToStatus[tokenId] = Status(uint(tokenToStatus[tokenId]) + 1);
tokenToCanvasData[tokenId] = dream;
emit Terraformed(tokenId, msg.sender);
}
/// @notice On transfer, revokes authorization to commit dreaming token
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
virtual
override
{
super._beforeTokenTransfer(from, to, tokenId);
tokenToAuthorizedDreamer[tokenId] = address(0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./TerraformsDreaming.sol";
/// @author xaltgeist
/// @title Pseudorandom token placements
abstract contract TerraformsPlacements is TerraformsDreaming {
uint public seed; // Seed derived from blockhash, used to rotate placements
mapping(uint => uint) public tokenToPlacement; // Pseudorandom placements
uint public immutable REVEAL_TIMESTAMP; // Token reveal (if not minted out)
uint[MAX_SUPPLY] placementShuffler; // Used for pseudorandom placements
event TokensRevealed(uint timestamp, uint seed);
constructor (){
REVEAL_TIMESTAMP = block.timestamp + 7 days;
}
/// @notice Finalizes the seed used to randomize token placement
/// @dev Requires that seed isn't set, and that either the supply is minted
/// or a week has elapsed since deploy
function setSeed() public {
require(
seed == 0 &&
(tokenCounter >= SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)
);
seed = uint(blockhash(block.number - 1)) % MAX_SUPPLY;
if (seed == 0) { // Don't allow seed to be 0
seed = 1;
}
emit TokensRevealed(block.timestamp, seed);
}
/// @notice Creates initial placements to determine a token's level/tile
/// @dev Initial pseudorandom placements will be rotated by the seed
function _shufflePlacements() internal {
uint max = MAX_SUPPLY - tokenCounter;
uint result;
uint next = uint(
keccak256(
abi.encodePacked(
tokenCounter,
blockhash(block.number - 1),
block.difficulty
)
)
) % max;
if (placementShuffler[next] == 0) {
result = next;
} else {
result = placementShuffler[next];
}
if (placementShuffler[max - 1] != 0) {
placementShuffler[next] = placementShuffler[max - 1];
} else {
placementShuffler[next] = max - 1;
}
tokenToPlacement[tokenCounter + 1] = result;
}
}
|
Owner can add new opt-in tokenURI address newAddress The new tokenURI address
|
function addTokenURIAddress(address newAddress) public onlyOwner {
tokenURIAddresses.push(newAddress);
}
| 13,120,769
|
pragma solidity ^0.5.11;
import "openzeppelin-solidity/contracts/payment/escrow/RefundEscrow.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./lifecycle/Finalizable.sol";
import "./lifecycle/Timelock.sol";
/**
* @title RefundableTask
* @dev Allows creation of refundable task contract.
*/
contract RefundableTask is Finalizable, Timelock {
using SafeMath for uint256;
// Task state
enum State { Active, Dispute, Success, Failure }
event StateChanged(State oldState, State newState);
event TaskFinished(string solutionUri);
// Task uri
string private _uri;
// Task solution uri
string private _solutionUri;
// Task state
State private _state;
// Arbitrator that is going to close or enableRefunds for this task
address private _arbitrator;
// Refund escrow used to hold funds while task is running
RefundEscrow private _escrow;
/**
* @dev Constructor, creates RefundableTask contract.
* @param uri String URI where task info is located.
* @param endTime The timestamp when lock release is enabled.
* @param beneficiary address of the beneficiary to whom task is addressed.
* @param arbitrator address of the arbitrator who will intervene in case od dispute.
*/
constructor (string memory uri, uint256 endTime, address payable beneficiary, address arbitrator) public Timelock(endTime) {
require(bytes(uri).length != 0, "RefundableTask: task URI should not be empty");
require(beneficiary != address(0), "RefundableTask: Beneficiary address should not be 0x0");
require(arbitrator != address(0), "RefundableTask: Arbitrator address should not be 0x0");
require(beneficiary != arbitrator, "RefundableTask: Beneficiary and arbitrator should not be the same account");
_uri = uri;
_state = State.Active;
_arbitrator = arbitrator;
_escrow = new RefundEscrow(beneficiary);
}
/// @return Checks if provided state Success or Failure.
function isFinalState(State nextState) private pure returns (bool) {
return nextState == State.Success || nextState == State.Failure;
}
/// @dev Throws if called with any state other than Success or Failure.
modifier onlyFinalState(State nextState) {
require(isFinalState(nextState), "RefundableTask: final state can only be Success or Failure");
_;
}
/// @dev Throws if called by any account other than the beneficiary.
modifier onlyBeneficiary() {
require(msg.sender == _escrow.beneficiary(), "RefundableTask: caller is not the beneficiary");
_;
}
/// @dev Throws if called by any account other than the arbitrator.
modifier onlyArbitrer() {
require(msg.sender == _arbitrator, "RefundableTask: caller is not the arbitrator");
_;
}
/// @return The URI that holds information for this task.
function uri() public view returns (string memory) {
return _uri;
}
/// @return The URI that holds information for this task's solution.
function solutionUri() public view returns (string memory) {
return _solutionUri;
}
/// @return The current state of the escrow.
function state() public view returns (State) {
return _state;
}
/// @return The beneficiary of the task.
function beneficiary() public view returns (address) {
return _escrow.beneficiary();
}
/// @return The arbitrator of the task.
function arbitrator() public view returns (address) {
return _arbitrator;
}
/// @return Whether task is finished.
function isFinished() public view returns (bool) {
return bytes(_solutionUri).length > 0;
}
/// @return Whether task is resolved.
function isResolved() public view returns (bool) {
return isFinalState(_state);
}
/// @return Returns task total allocated funds.
function taskBalance() public view returns (uint256) {
return address(_escrow).balance;
}
/// @dev Fallback function used for ask fund forwarding.
function () external payable {
require(!isResolved(), "RefundableTask: can only accept funds while task in progress");
if (_state == State.Active) {
fundTask(msg.sender);
} else {
fundDisputeResolution();
}
}
/**
* @dev Task fund forwarding, sending funds to escrow.
* @param refundee The address funds will be sent to if a refund occurs.
*/
function fundTask(address refundee) public payable {
require(_state == State.Active, "RefundableTask: can only fund task while active");
require(refundee != address(0), "RefundableTask: refundee address should not be 0x0");
_escrow.deposit.value(msg.value)(refundee);
}
/// @dev Dispute resolution fund forwarding.
function fundDisputeResolution() public payable {
require(_state == State.Dispute, "RefundableTask: can only fund dispute resolution while in dispute");
}
/**
* @dev Investors can claim refunds here if task is unsuccessful.
* @param refundee Whose refund will be claimed.
*/
function claimRefund(address payable refundee) public {
require(isFinalized(), "RefundableTask: task contract should be finalized");
require(_state == State.Failure, "RefundableTask: refunds available only if task was a failure");
_escrow.withdraw(refundee);
}
/**
* @dev Finish this task providing a solution.
* @param solutionUri_ Solution URI for this task.
*/
function finish(string memory solutionUri_) public onlyBeneficiary {
require(_state == State.Active, "RefundableTask: can only finish task while active");
require(bytes(solutionUri_).length != 0, "RefundableTask: solution URI should not be empty");
_solutionUri = solutionUri_;
emit TaskFinished(_solutionUri);
}
/// @dev Accept this task on owner request.
function accept() public onlyOwner {
require(_state == State.Active, "RefundableTask: can only accept task while active");
require(isFinished(), "RefundableTask: can only accept task if finished");
finalize(State.Success);
}
/// @dev Fail this task because of timeout.
function timeout() public {
require(!isResolved(), "RefundableTask: can not timeout if task already resolved");
require(!isLocked(), "RefundableTask: can not timeout if task is still locked");
finalize(State.Failure);
}
/// @dev Fail this task on beneficiary request.
function cancel() public onlyBeneficiary {
require(_state == State.Active, "RefundableTask: can only cancel task while active");
finalize(State.Failure);
}
/// @dev Raise dispute for this task on beneficiary request.
function raiseDispute() public payable onlyBeneficiary {
require(_state == State.Active, "RefundableTask: can only raise dispute while active");
require(isFinished(), "RefundableTask: can only raise dispute if task finished");
emit StateChanged(_state, State.Dispute);
_state = State.Dispute;
}
/**
* @dev Resolve dispute for this task.
* @param newState The new state that will solve the dispute.
*/
function resolveDispute(State newState) public onlyArbitrer {
require(_state == State.Dispute, "RefundableTask: can only resolve dispute while in dispute");
finalize(newState);
}
/// @dev Transfer all Ether held by the contract to the owner.
function reclaimEther() external onlyOwner onlyFinalState(_state) {
address payable _owner = address(uint160(owner()));
_owner.transfer(address(this).balance);
}
/**
* @dev Move contract to a final state.
* @param newState The final state.
*/
function finalize(State newState) private {
emit StateChanged(_state, newState);
_state = newState;
_transferOwnership(msg.sender);
finalize();
}
/// @dev Finalization task, called when finalize() is called.
function _finalization() internal onlyFinalState(_state) {
if (_state == State.Success) {
_escrow.close();
_escrow.beneficiaryWithdraw();
} else {
_escrow.enableRefunds();
}
super._finalization();
}
}
|
Finalization task, called when finalize() is called.
|
function _finalization() internal onlyFinalState(_state) {
if (_state == State.Success) {
_escrow.close();
_escrow.beneficiaryWithdraw();
_escrow.enableRefunds();
}
super._finalization();
}
| 5,511,591
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/**
* @title Linked to ILV Marker Interface
*
* @notice Marks smart contracts which are linked to IlluviumERC20 token instance upon construction,
* all these smart contracts share a common ilv() address getter
*
* @notice Implementing smart contracts MUST verify that they get linked to real IlluviumERC20 instance
* and that ilv() getter returns this very same instance address
*
* @author Basil Gorin
*/
interface ILinkedToILV {
/**
* @notice Getter for a verified IlluviumERC20 instance address
*
* @return IlluviumERC20 token instance address smart contract is linked to
*/
function ilv() external view returns (address);
}
/**
* @title Illuvium Pool
*
* @notice An abstraction representing a pool, see IlluviumPoolBase for details
*
* @author Pedro Bergamini, reviewed by Basil Gorin
*/
interface IPool is ILinkedToILV {
/**
* @dev Deposit is a key data structure used in staking,
* it represents a unit of stake with its amount, weight and term (time interval)
*/
struct Deposit {
// @dev token amount staked
uint256 tokenAmount;
// @dev stake weight
uint256 weight;
// @dev locking period - from
uint64 lockedFrom;
// @dev locking period - until
uint64 lockedUntil;
// @dev indicates if the stake was created as a yield reward
bool isYield;
}
// for the rest of the functions see Soldoc in IlluviumPoolBase
function silv() external view returns (address);
function poolToken() external view returns (address);
function isFlashPool() external view returns (bool);
function weight() external view returns (uint32);
function lastYieldDistribution() external view returns (uint64);
function yieldRewardsPerWeight() external view returns (uint256);
function usersLockingWeight() external view returns (uint256);
function pendingYieldRewards(address _user) external view returns (uint256);
function balanceOf(address _user) external view returns (uint256);
function getDeposit(address _user, uint256 _depositId) external view returns (Deposit memory);
function getDepositsLength(address _user) external view returns (uint256);
function stake(
uint256 _amount,
uint64 _lockedUntil,
bool useSILV
) external;
function unstake(
uint256 _depositId,
uint256 _amount,
bool useSILV
) external;
function sync() external;
function processRewards(bool useSILV) external;
function setWeight(uint32 _weight) external;
}
interface ICorePool is IPool {
function vaultRewardsPerToken() external view returns (uint256);
function poolTokenReserve() external view returns (uint256);
function stakeAsPool(address _staker, uint256 _amount) external;
function receiveVaultRewards(uint256 _amount) external;
}
/**
* @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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = msg.sender;
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual 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;
}
}
/**
* @title Address Utils
*
* @dev Utility library of inline functions on addresses
*
* @author Basil Gorin
*/
library AddressUtils {
/**
* @notice Checks if the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
// a variable to load `extcodesize` to
uint256 size = 0;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works.
// TODO: Check this again before the Serenity release, because all addresses will be contracts.
// solium-disable-next-line security/no-inline-assembly
assembly {
// retrieve the size of the code at address `addr`
size := extcodesize(addr)
}
// positive size indicates a smart contract address
return size > 0;
}
}
/**
* @title ERC20 token receiver interface
*
* @dev Interface for any contract that wants to support safe transfers
* from ERC20 token smart contracts.
* @dev Inspired by ERC721 and ERC223 token standards
*
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
* @dev See https://github.com/ethereum/EIPs/issues/223
*
* @author Basil Gorin
*/
interface ERC20Receiver {
/**
* @notice Handle the receipt of a ERC20 token(s)
* @dev The ERC20 smart contract calls this function on the recipient
* after a successful transfer (`safeTransferFrom`).
* This function MAY throw to revert and reject the transfer.
* Return of other than the magic value MUST result in the transaction being reverted.
* @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.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _value amount of tokens which is being transferred
* @param _data additional data with no specified format
* @return `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))` unless throwing
*/
function onERC20Received(address _operator, address _from, uint256 _value, bytes calldata _data) external returns(bytes4);
}
/**
* @title Access Control List
*
* @notice Access control smart contract provides an API to check
* if specific operation is permitted globally and/or
* if particular user has a permission to execute it.
*
* @notice It deals with two main entities: features and roles.
*
* @notice Features are designed to be used to enable/disable specific
* functions (public functions) of the smart contract for everyone.
* @notice User roles are designed to restrict access to specific
* functions (restricted functions) of the smart contract to some users.
*
* @notice Terms "role", "permissions" and "set of permissions" have equal meaning
* in the documentation text and may be used interchangeably.
* @notice Terms "permission", "single permission" implies only one permission bit set.
*
* @dev This smart contract is designed to be inherited by other
* smart contracts which require access control management capabilities.
*
* @author Basil Gorin
*/
contract AccessControl {
/**
* @notice Access manager is responsible for assigning the roles to users,
* enabling/disabling global features of the smart contract
* @notice Access manager can add, remove and update user roles,
* remove and update global features
*
* @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features
* @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled
*/
uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000;
/**
* @dev Bitmask representing all the possible permissions (super admin role)
* @dev Has all the bits are enabled (2^256 - 1 value)
*/
uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF...
/**
* @notice Privileged addresses with defined roles/permissions
* @notice In the context of ERC20/ERC721 tokens these can be permissions to
* allow minting or burning tokens, transferring on behalf and so on
*
* @dev Maps user address to the permissions bitmask (role), where each bit
* represents a permission
* @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
* represents all possible permissions
* @dev Zero address mapping represents global features of the smart contract
*/
mapping(address => uint256) public userRoles;
/**
* @dev Fired in updateRole() and updateFeatures()
*
* @param _by operator which called the function
* @param _to address which was granted/revoked permissions
* @param _requested permissions requested
* @param _actual permissions effectively set
*/
event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual);
/**
* @notice Creates an access control instance,
* setting contract creator to have full privileges
*/
constructor() {
// contract creator has full privileges
userRoles[msg.sender] = FULL_PRIVILEGES_MASK;
}
/**
* @notice Retrieves globally set of features enabled
*
* @dev Auxiliary getter function to maintain compatibility with previous
* versions of the Access Control List smart contract, where
* features was a separate uint256 public field
*
* @return 256-bit bitmask of the features enabled
*/
function features() public view returns(uint256) {
// according to new design features are stored in zero address
// mapping of `userRoles` structure
return userRoles[address(0)];
}
/**
* @notice Updates set of the globally enabled features (`features`),
* taking into account sender's permissions
*
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
* @dev Function is left for backward compatibility with older versions
*
* @param _mask bitmask representing a set of features to enable/disable
*/
function updateFeatures(uint256 _mask) public {
// delegate call to `updateRole`
updateRole(address(0), _mask);
}
/**
* @notice Updates set of permissions (role) for a given user,
* taking into account sender's permissions.
*
* @dev Setting role to zero is equivalent to removing an all permissions
* @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to
* copying senders' permissions (role) to the user
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
*
* @param operator address of a user to alter permissions for or zero
* to alter global features of the smart contract
* @param role bitmask representing a set of permissions to
* enable/disable for a user specified
*/
function updateRole(address operator, uint256 role) public {
// caller must have a permission to update user roles
require(isSenderInRole(ROLE_ACCESS_MANAGER), "insufficient privileges (ROLE_ACCESS_MANAGER required)");
// evaluate the role and reassign it
userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role);
// fire an event
emit RoleUpdated(msg.sender, operator, role, userRoles[operator]);
}
/**
* @notice Determines the permission bitmask an operator can set on the
* target permission set
* @notice Used to calculate the permission bitmask to be set when requested
* in `updateRole` and `updateFeatures` functions
*
* @dev Calculated based on:
* 1) operator's own permission set read from userRoles[operator]
* 2) target permission set - what is already set on the target
* 3) desired permission set - what do we want set target to
*
* @dev Corner cases:
* 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`:
* `desired` bitset is returned regardless of the `target` permission set value
* (what operator sets is what they get)
* 2) Operator with no permissions (zero bitset):
* `target` bitset is returned regardless of the `desired` value
* (operator has no authority and cannot modify anything)
*
* @dev Example:
* Consider an operator with the permissions bitmask 00001111
* is about to modify the target permission set 01010101
* Operator wants to set that permission set to 00110011
* Based on their role, an operator has the permissions
* to update only lowest 4 bits on the target, meaning that
* high 4 bits of the target set in this example is left
* unchanged and low 4 bits get changed as desired: 01010011
*
* @param operator address of the contract operator which is about to set the permissions
* @param target input set of permissions to operator is going to modify
* @param desired desired set of permissions operator would like to set
* @return resulting set of permissions given operator will set
*/
function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) {
// read operator's permissions
uint256 p = userRoles[operator];
// taking into account operator's permissions,
// 1) enable the permissions desired on the `target`
target |= p & desired;
// 2) disable the permissions desired on the `target`
target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired));
// return calculated result
return target;
}
/**
* @notice Checks if requested set of features is enabled globally on the contract
*
* @param required set of features to check against
* @return true if all the features requested are enabled, false otherwise
*/
function isFeatureEnabled(uint256 required) public view returns(bool) {
// delegate call to `__hasRole`, passing `features` property
return __hasRole(features(), required);
}
/**
* @notice Checks if transaction sender `msg.sender` has all the permissions required
*
* @param required set of permissions (role) to check against
* @return true if all the permissions requested are enabled, false otherwise
*/
function isSenderInRole(uint256 required) public view returns(bool) {
// delegate call to `isOperatorInRole`, passing transaction sender
return isOperatorInRole(msg.sender, required);
}
/**
* @notice Checks if operator has all the permissions (role) required
*
* @param operator address of the user to check role for
* @param required set of permissions (role) to check
* @return true if all the permissions requested are enabled, false otherwise
*/
function isOperatorInRole(address operator, uint256 required) public view returns(bool) {
// delegate call to `__hasRole`, passing operator's permissions (role)
return __hasRole(userRoles[operator], required);
}
/**
* @dev Checks if role `actual` contains all the permissions required `required`
*
* @param actual existent role
* @param required required role
* @return true if actual has required role (all permissions), false otherwise
*/
function __hasRole(uint256 actual, uint256 required) internal pure returns(bool) {
// check the bitmask for the role required and return the result
return actual & required == required;
}
}
/**
* @title Illuvium (ILV) ERC20 token
*
* @notice Illuvium is a core ERC20 token powering the game.
* It serves as an in-game currency, is tradable on exchanges,
* it powers up the governance protocol (Illuvium DAO) and participates in Yield Farming.
*
* @dev Token Summary:
* - Symbol: ILV
* - Name: Illuvium
* - Decimals: 18
* - Initial token supply: 7,000,000 ILV
* - Maximum final token supply: 10,000,000 ILV
* - Up to 3,000,000 ILV may get minted in 3 years period via yield farming
* - Mintable: total supply may increase
* - Burnable: total supply may decrease
*
* @dev Token balances and total supply are effectively 192 bits long, meaning that maximum
* possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens)
*
* @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe.
* Additionally, Solidity 0.8.1 enforces overflow/underflow safety.
*
* @dev ERC20: reviewed according to https://eips.ethereum.org/EIPS/eip-20
*
* @dev ERC20: contract has passed OpenZeppelin ERC20 tests,
* see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js
* see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js
* see adopted copies of these tests in the `test` folder
*
* @dev ERC223/ERC777: not supported;
* send tokens via `safeTransferFrom` and implement `ERC20Receiver.onERC20Received` on the receiver instead
*
* @dev Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) - resolved
* Related events and functions are marked with "ISBN:978-1-7281-3027-9" tag:
* - event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value)
* - event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value)
* - function increaseAllowance(address _spender, uint256 _value) public returns (bool)
* - function decreaseAllowance(address _spender, uint256 _value) public returns (bool)
* See: https://ieeexplore.ieee.org/document/8802438
* See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* @author Basil Gorin
*/
contract IlluviumERC20 is AccessControl {
/**
* @dev Smart contract unique identifier, a random number
* @dev Should be regenerated each time smart contact source code is changed
* and changes smart contract itself is to be redeployed
* @dev Generated using https://www.random.org/bytes/
*/
uint256 public constant TOKEN_UID = 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c;
/**
* @notice Name of the token: Illuvium
*
* @notice ERC20 name of the token (long name)
*
* @dev ERC20 `function name() public view returns (string)`
*
* @dev Field is declared public: getter name() is created when compiled,
* it returns the name of the token.
*/
string public constant name = "Illuvium";
/**
* @notice Symbol of the token: ILV
*
* @notice ERC20 symbol of that token (short name)
*
* @dev ERC20 `function symbol() public view returns (string)`
*
* @dev Field is declared public: getter symbol() is created when compiled,
* it returns the symbol of the token
*/
string public constant symbol = "ILV";
/**
* @notice Decimals of the token: 18
*
* @dev ERC20 `function decimals() public view returns (uint8)`
*
* @dev Field is declared public: getter decimals() is created when compiled,
* it returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should
* be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`).
*
* @dev NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including balanceOf() and transfer().
*/
uint8 public constant decimals = 18;
/**
* @notice Total supply of the token: initially 7,000,000,
* with the potential to grow up to 10,000,000 during yield farming period (3 years)
*
* @dev ERC20 `function totalSupply() public view returns (uint256)`
*
* @dev Field is declared public: getter totalSupply() is created when compiled,
* it returns the amount of tokens in existence.
*/
uint256 public totalSupply; // is set to 7 million * 10^18 in the constructor
/**
* @dev A record of all the token balances
* @dev This mapping keeps record of all token owners:
* owner => balance
*/
mapping(address => uint256) public tokenBalances;
/**
* @notice A record of each account's voting delegate
*
* @dev Auxiliary data structure used to sum up an account's voting power
*
* @dev This mapping keeps record of all voting power delegations:
* voting delegator (token owner) => voting delegate
*/
mapping(address => address) public votingDelegates;
/**
* @notice A voting power record binds voting power of a delegate to a particular
* block when the voting power delegation change happened
*/
struct VotingPowerRecord {
/*
* @dev block.number when delegation has changed; starting from
* that block voting power value is in effect
*/
uint64 blockNumber;
/*
* @dev cumulative voting power a delegate has obtained starting
* from the block stored in blockNumber
*/
uint192 votingPower;
}
/**
* @notice A record of each account's voting power
*
* @dev Primarily data structure to store voting power for each account.
* Voting power sums up from the account's token balance and delegated
* balances.
*
* @dev Stores current value and entire history of its changes.
* The changes are stored as an array of checkpoints.
* Checkpoint is an auxiliary data structure containing voting
* power (number of votes) and block number when the checkpoint is saved
*
* @dev Maps voting delegate => voting power record
*/
mapping(address => VotingPowerRecord[]) public votingPowerHistory;
/**
* @dev A record of nonces for signing/validating signatures in `delegateWithSig`
* for every delegate, increases after successful validation
*
* @dev Maps delegate address => delegate nonce
*/
mapping(address => uint256) public nonces;
/**
* @notice A record of all the allowances to spend tokens on behalf
* @dev Maps token owner address to an address approved to spend
* some tokens on behalf, maps approved address to that amount
* @dev owner => spender => value
*/
mapping(address => mapping(address => uint256)) public transferAllowances;
/**
* @notice Enables ERC20 transfers of the tokens
* (transfer by the token owner himself)
* @dev Feature FEATURE_TRANSFERS must be enabled in order for
* `transfer()` function to succeed
*/
uint32 public constant FEATURE_TRANSFERS = 0x0000_0001;
/**
* @notice Enables ERC20 transfers on behalf
* (transfer by someone else on behalf of token owner)
* @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for
* `transferFrom()` function to succeed
* @dev Token owner must call `approve()` first to authorize
* the transfer on behalf
*/
uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002;
/**
* @dev Defines if the default behavior of `transfer` and `transferFrom`
* checks if the receiver smart contract supports ERC20 tokens
* @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not
* check if the receiver smart contract supports ERC20 tokens,
* i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom`
* @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers
* check if the receiver smart contract supports ERC20 tokens,
* i.e. `transfer` and `transferFrom` behave like `safeTransferFrom`
*/
uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004;
/**
* @notice Enables token owners to burn their own tokens,
* including locked tokens which are burnt first
* @dev Feature FEATURE_OWN_BURNS must be enabled in order for
* `burn()` function to succeed when called by token owner
*/
uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008;
/**
* @notice Enables approved operators to burn tokens on behalf of their owners,
* including locked tokens which are burnt first
* @dev Feature FEATURE_OWN_BURNS must be enabled in order for
* `burn()` function to succeed when called by approved operator
*/
uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010;
/**
* @notice Enables delegators to elect delegates
* @dev Feature FEATURE_DELEGATIONS must be enabled in order for
* `delegate()` function to succeed
*/
uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020;
/**
* @notice Enables delegators to elect delegates on behalf
* (via an EIP712 signature)
* @dev Feature FEATURE_DELEGATIONS must be enabled in order for
* `delegateWithSig()` function to succeed
*/
uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040;
/**
* @notice Token creator is responsible for creating (minting)
* tokens to an arbitrary address
* @dev Role ROLE_TOKEN_CREATOR allows minting tokens
* (calling `mint` function)
*/
uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000;
/**
* @notice Token destroyer is responsible for destroying (burning)
* tokens owned by an arbitrary address
* @dev Role ROLE_TOKEN_DESTROYER allows burning tokens
* (calling `burn` function)
*/
uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000;
/**
* @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks,
* which may be useful to simplify tokens transfers into "legacy" smart contracts
* @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having
* `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens
* via `transfer` and `transferFrom` functions in the same way they
* would via `unsafeTransferFrom` function
* @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission
* doesn't affect the transfer behaviour since
* `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
* @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER
*/
uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000;
/**
* @notice ERC20 senders are allowed to send tokens without ERC20 safety checks,
* which may be useful to simplify tokens transfers into "legacy" smart contracts
* @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having
* `ROLE_ERC20_SENDER` permission are allowed to send tokens
* via `transfer` and `transferFrom` functions in the same way they
* would via `unsafeTransferFrom` function
* @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission
* doesn't affect the transfer behaviour since
* `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver
* @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER
*/
uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000;
/**
* @dev Magic value to be returned by ERC20Receiver upon successful reception of token(s)
* @dev Equal to `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC20Receiver(address(0)).onERC20Received.selector`
*/
bytes4 private constant ERC20_RECEIVED = 0x4fc35859;
/**
* @notice EIP-712 contract's domain typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/**
* @notice EIP-712 delegation struct typeHash, see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash
*/
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)");
/**
* @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions
*
* @dev ERC20 `event Transfer(address indexed _from, address indexed _to, uint256 _value)`
*
* @param _from an address tokens were consumed from
* @param _to an address tokens were sent to
* @param _value number of tokens transferred
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Fired in approve() and approveAtomic() functions
*
* @dev ERC20 `event Approval(address indexed _owner, address indexed _spender, uint256 _value)`
*
* @param _owner an address which granted a permission to transfer
* tokens on its behalf
* @param _spender an address which received a permission to transfer
* tokens on behalf of the owner `_owner`
* @param _value amount of tokens granted to transfer on behalf
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @dev Fired in mint() function
*
* @param _by an address which minted some tokens (transaction sender)
* @param _to an address the tokens were minted to
* @param _value an amount of tokens minted
*/
event Minted(address indexed _by, address indexed _to, uint256 _value);
/**
* @dev Fired in burn() function
*
* @param _by an address which burned some tokens (transaction sender)
* @param _from an address the tokens were burnt from
* @param _value an amount of tokens burnt
*/
event Burnt(address indexed _by, address indexed _from, uint256 _value);
/**
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer
*
* @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions
*
* @param _by an address which performed the transfer
* @param _from an address tokens were consumed from
* @param _to an address tokens were sent to
* @param _value number of tokens transferred
*/
event Transferred(address indexed _by, address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Similar to ERC20 Approve event, but also logs old approval value
*
* @dev Fired in approve() and approveAtomic() functions
*
* @param _owner an address which granted a permission to transfer
* tokens on its behalf
* @param _spender an address which received a permission to transfer
* tokens on behalf of the owner `_owner`
* @param _oldValue previously granted amount of tokens to transfer on behalf
* @param _value new granted amount of tokens to transfer on behalf
*/
event Approved(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value);
/**
* @dev Notifies that a key-value pair in `votingDelegates` mapping has changed,
* i.e. a delegator address has changed its delegate address
*
* @param _of delegator address, a token owner
* @param _from old delegate, an address which delegate right is revoked
* @param _to new delegate, an address which received the voting power
*/
event DelegateChanged(address indexed _of, address indexed _from, address indexed _to);
/**
* @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed,
* i.e. a delegate's voting power has changed.
*
* @param _of delegate whose voting power has changed
* @param _fromVal previous number of votes delegate had
* @param _toVal new number of votes delegate has
*/
event VotingPowerChanged(address indexed _of, uint256 _fromVal, uint256 _toVal);
/**
* @dev Deploys the token smart contract,
* assigns initial token supply to the address specified
*
* @param _initialHolder owner of the initial token supply
*/
constructor(address _initialHolder) {
// verify initial holder address non-zero (is set)
require(_initialHolder != address(0), "_initialHolder not set (zero address)");
// mint initial supply
mint(_initialHolder, 7_000_000e18);
}
// ===== Start: ERC20/ERC223/ERC777 functions =====
/**
* @notice Gets the balance of a particular address
*
* @dev ERC20 `function balanceOf(address _owner) public view returns (uint256 balance)`
*
* @param _owner the address to query the the balance for
* @return balance an amount of tokens owned by the address specified
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
// read the balance and return
return tokenBalances[_owner];
}
/**
* @notice Transfers some tokens to an external address or a smart contract
*
* @dev ERC20 `function transfer(address _to, uint256 _value) public returns (bool success)`
*
* @dev Called by token owner (an address which has a
* positive token balance tracked by this smart contract)
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * self address or
* * smart contract which doesn't support ERC20
*
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
* @return success true on success, throws otherwise
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
// just delegate call to `transferFrom`,
// `FEATURE_TRANSFERS` is verified inside it
return transferFrom(msg.sender, _to, _value);
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev ERC20 `function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)`
*
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC20
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
* @return success true on success, throws otherwise
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
// depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default)
// or unsafe transfer
// if `FEATURE_UNSAFE_TRANSFERS` is enabled
// or receiver has `ROLE_ERC20_RECEIVER` permission
// or sender has `ROLE_ERC20_SENDER` permission
if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS)
|| isOperatorInRole(_to, ROLE_ERC20_RECEIVER)
|| isSenderInRole(ROLE_ERC20_SENDER)) {
// we execute unsafe transfer - delegate call to `unsafeTransferFrom`,
// `FEATURE_TRANSFERS` is verified inside it
unsafeTransferFrom(_from, _to, _value);
}
// otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled
// and receiver doesn't have `ROLE_ERC20_RECEIVER` permission
else {
// we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`,
// `FEATURE_TRANSFERS` is verified inside it
safeTransferFrom(_from, _to, _value, "");
}
// both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so
// if we're here - it means operation successful,
// just return true
return true;
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev Inspired by ERC721 safeTransferFrom, this function allows to
* send arbitrary data to the receiver on successful token transfer
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* * smart contract which doesn't support ERC20Receiver interface
* @dev Returns silently on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
* @param _data [optional] additional data with no specified format,
* sent in onERC20Received call to `_to` in case if its a smart contract
*/
function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public {
// first delegate call to `unsafeTransferFrom`
// to perform the unsafe token(s) transfer
unsafeTransferFrom(_from, _to, _value);
// after the successful transfer - check if receiver supports
// ERC20Receiver and execute a callback handler `onERC20Received`,
// reverting whole transaction on any error:
// check if receiver `_to` supports ERC20Receiver interface
if(AddressUtils.isContract(_to)) {
// if `_to` is a contract - execute onERC20Received
bytes4 response = ERC20Receiver(_to).onERC20Received(msg.sender, _from, _value, _data);
// expected response is ERC20_RECEIVED
require(response == ERC20_RECEIVED, "invalid onERC20Received response");
}
}
/**
* @notice Transfers some tokens on behalf of address `_from' (token owner)
* to some other address `_to`
*
* @dev In contrast to `safeTransferFrom` doesn't check recipient
* smart contract to support ERC20 tokens (ERC20Receiver)
* @dev Designed to be used by developers when the receiver is known
* to support ERC20 tokens but doesn't implement ERC20Receiver interface
* @dev Called by token owner on his own or approved address,
* an address approved earlier by token owner to
* transfer some amount of tokens on its behalf
* @dev Throws on any error like
* * insufficient token balance or
* * incorrect `_to` address:
* * zero address or
* * same as `_from` address (self transfer)
* @dev Returns silently on success, throws otherwise
*
* @param _from token owner which approved caller (transaction sender)
* to transfer `_value` of tokens on its behalf
* @param _to an address to transfer tokens to,
* must be either an external address or a smart contract,
* compliant with the ERC20 standard
* @param _value amount of tokens to be transferred, must
* be greater than zero
*/
function unsafeTransferFrom(address _from, address _to, uint256 _value) public {
// if `_from` is equal to sender, require transfers feature to be enabled
// otherwise require transfers on behalf feature to be enabled
require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS)
|| _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF),
_from == msg.sender? "transfers are disabled": "transfers on behalf are disabled");
// non-zero source address check - Zeppelin
// obviously, zero source address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
// since for zero value transfer transaction succeeds otherwise
require(_from != address(0), "ERC20: transfer from the zero address"); // Zeppelin msg
// non-zero recipient address check
require(_to != address(0), "ERC20: transfer to the zero address"); // Zeppelin msg
// sender and recipient cannot be the same
require(_from != _to, "sender and recipient are the same (_from = _to)");
// sending tokens to the token smart contract itself is a client mistake
require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)");
// according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20
// "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event."
if(_value == 0) {
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
// don't forget to return - we're done
return;
}
// no need to make arithmetic overflow check on the _value - by design of mint()
// in case of transfer on behalf
if(_from != msg.sender) {
// read allowance value - the amount of tokens allowed to transfer - into the stack
uint256 _allowance = transferAllowances[_from][msg.sender];
// verify sender has an allowance to transfer amount of tokens requested
require(_allowance >= _value, "ERC20: transfer amount exceeds allowance"); // Zeppelin msg
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][msg.sender] = _allowance;
// emit an improved atomic approve event
emit Approved(_from, msg.sender, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, msg.sender, _allowance);
}
// verify sender has enough tokens to transfer on behalf
require(tokenBalances[_from] >= _value, "ERC20: transfer amount exceeds balance"); // Zeppelin msg
// perform the transfer:
// decrease token owner (sender) balance
tokenBalances[_from] -= _value;
// increase `_to` address (receiver) balance
tokenBalances[_to] += _value;
// move voting power associated with the tokens transferred
__moveVotingPower(votingDelegates[_from], votingDelegates[_to], _value);
// emit an improved transfer event
emit Transferred(msg.sender, _from, _to, _value);
// emit an ERC20 transfer event
emit Transfer(_from, _to, _value);
}
/**
* @notice Approves address called `_spender` to transfer some amount
* of tokens on behalf of the owner
*
* @dev ERC20 `function approve(address _spender, uint256 _value) public returns (bool success)`
*
* @dev Caller must not necessarily own any tokens to grant the permission
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens spender `_spender` is allowed to
* transfer on behalf of the token owner
* @return success true on success, throws otherwise
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
// non-zero spender address check - Zeppelin
// obviously, zero spender address is a client mistake
// it's not part of ERC20 standard but it's reasonable to fail fast
require(_spender != address(0), "ERC20: approve to the zero address"); // Zeppelin msg
// read old approval value to emmit an improved event (ISBN:978-1-7281-3027-9)
uint256 _oldValue = transferAllowances[msg.sender][_spender];
// perform an operation: write value requested into the storage
transferAllowances[msg.sender][_spender] = _value;
// emit an improved atomic approve event (ISBN:978-1-7281-3027-9)
emit Approved(msg.sender, _spender, _oldValue, _value);
// emit an ERC20 approval event
emit Approval(msg.sender, _spender, _value);
// operation successful, return true
return true;
}
/**
* @notice Returns the amount which _spender is still allowed to withdraw from _owner.
*
* @dev ERC20 `function allowance(address _owner, address _spender) public view returns (uint256 remaining)`
*
* @dev A function to check an amount of tokens owner approved
* to transfer on its behalf by some other address called "spender"
*
* @param _owner an address which approves transferring some tokens on its behalf
* @param _spender an address approved to transfer some tokens on behalf
* @return remaining an amount of tokens approved address `_spender` can transfer on behalf
* of token owner `_owner`
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
// read the value from storage and return
return transferAllowances[_owner][_spender];
}
// ===== End: ERC20/ERC223/ERC777 functions =====
// ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) =====
/**
* @notice Increases the allowance granted to `spender` by the transaction sender
*
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Throws if value to increase by is zero or too big and causes arithmetic overflow
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens to increase by
* @return success true on success, throws otherwise
*/
function increaseAllowance(address _spender, uint256 _value) public virtual returns (bool) {
// read current allowance value
uint256 currentVal = transferAllowances[msg.sender][_spender];
// non-zero _value and arithmetic overflow check on the allowance
require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow");
// delegate call to `approve` with the new value
return approve(_spender, currentVal + _value);
}
/**
* @notice Decreases the allowance granted to `spender` by the caller.
*
* @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9)
*
* @dev Throws if value to decrease by is zero or is bigger than currently allowed value
*
* @param _spender an address approved by the caller (token owner)
* to spend some tokens on its behalf
* @param _value an amount of tokens to decrease by
* @return success true on success, throws otherwise
*/
function decreaseAllowance(address _spender, uint256 _value) public virtual returns (bool) {
// read current allowance value
uint256 currentVal = transferAllowances[msg.sender][_spender];
// non-zero _value check on the allowance
require(_value > 0, "zero value approval decrease");
// verify allowance decrease doesn't underflow
require(currentVal >= _value, "ERC20: decreased allowance below zero");
// delegate call to `approve` with the new value
return approve(_spender, currentVal - _value);
}
// ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (ISBN:978-1-7281-3027-9) =====
// ===== Start: Minting/burning extension =====
/**
* @dev Mints (creates) some tokens to address specified
* @dev The value specified is treated as is without taking
* into account what `decimals` value is
* @dev Behaves effectively as `mintTo` function, allowing
* to specify an address to mint tokens to
* @dev Requires sender to have `ROLE_TOKEN_CREATOR` permission
*
* @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256
*
* @param _to an address to mint tokens to
* @param _value an amount of tokens to mint (create)
*/
function mint(address _to, uint256 _value) public {
// check if caller has sufficient permissions to mint tokens
require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)");
// non-zero recipient address check
require(_to != address(0), "ERC20: mint to the zero address"); // Zeppelin msg
// non-zero _value and arithmetic overflow check on the total supply
// this check automatically secures arithmetic overflow on the individual balance
require(totalSupply + _value > totalSupply, "zero value mint or arithmetic overflow");
// uint192 overflow check (required by voting delegation)
require(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)");
// perform mint:
// increase total amount of tokens value
totalSupply += _value;
// increase `_to` address balance
tokenBalances[_to] += _value;
// create voting power associated with the tokens minted
__moveVotingPower(address(0), votingDelegates[_to], _value);
// fire a minted event
emit Minted(msg.sender, _to, _value);
// emit an improved transfer event
emit Transferred(msg.sender, address(0), _to, _value);
// fire ERC20 compliant transfer event
emit Transfer(address(0), _to, _value);
}
/**
* @dev Burns (destroys) some tokens from the address specified
* @dev The value specified is treated as is without taking
* into account what `decimals` value is
* @dev Behaves effectively as `burnFrom` function, allowing
* to specify an address to burn tokens from
* @dev Requires sender to have `ROLE_TOKEN_DESTROYER` permission
*
* @param _from an address to burn some tokens from
* @param _value an amount of tokens to burn (destroy)
*/
function burn(address _from, uint256 _value) public {
// check if caller has sufficient permissions to burn tokens
// and if not - check for possibility to burn own tokens or to burn on behalf
if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) {
// if `_from` is equal to sender, require own burns feature to be enabled
// otherwise require burns on behalf feature to be enabled
require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS)
|| _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF),
_from == msg.sender? "burns are disabled": "burns on behalf are disabled");
// in case of burn on behalf
if(_from != msg.sender) {
// read allowance value - the amount of tokens allowed to be burnt - into the stack
uint256 _allowance = transferAllowances[_from][msg.sender];
// verify sender has an allowance to burn amount of tokens requested
require(_allowance >= _value, "ERC20: burn amount exceeds allowance"); // Zeppelin msg
// update allowance value on the stack
_allowance -= _value;
// update the allowance value in storage
transferAllowances[_from][msg.sender] = _allowance;
// emit an improved atomic approve event
emit Approved(msg.sender, _from, _allowance + _value, _allowance);
// emit an ERC20 approval event to reflect the decrease
emit Approval(_from, msg.sender, _allowance);
}
}
// at this point we know that either sender is ROLE_TOKEN_DESTROYER or
// we burn own tokens or on behalf (in latest case we already checked and updated allowances)
// we have left to execute balance checks and burning logic itself
// non-zero burn value check
require(_value != 0, "zero value burn");
// non-zero source address check - Zeppelin
require(_from != address(0), "ERC20: burn from the zero address"); // Zeppelin msg
// verify `_from` address has enough tokens to destroy
// (basically this is a arithmetic overflow check)
require(tokenBalances[_from] >= _value, "ERC20: burn amount exceeds balance"); // Zeppelin msg
// perform burn:
// decrease `_from` address balance
tokenBalances[_from] -= _value;
// decrease total amount of tokens value
totalSupply -= _value;
// destroy voting power associated with the tokens burnt
__moveVotingPower(votingDelegates[_from], address(0), _value);
// fire a burnt event
emit Burnt(msg.sender, _from, _value);
// emit an improved transfer event
emit Transferred(msg.sender, _from, address(0), _value);
// fire ERC20 compliant transfer event
emit Transfer(_from, address(0), _value);
}
// ===== End: Minting/burning extension =====
// ===== Start: DAO Support (Compound-like voting delegation) =====
/**
* @notice Gets current voting power of the account `_of`
* @param _of the address of account to get voting power of
* @return current cumulative voting power of the account,
* sum of token balances of all its voting delegators
*/
function getVotingPower(address _of) public view returns (uint256) {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// lookup the history and return latest element
return history.length == 0? 0: history[history.length - 1].votingPower;
}
/**
* @notice Gets past voting power of the account `_of` at some block `_blockNum`
* @dev Throws if `_blockNum` is not in the past (not the finalized block)
* @param _of the address of account to get voting power of
* @param _blockNum block number to get the voting power at
* @return past cumulative voting power of the account,
* sum of token balances of all its voting delegators at block number `_blockNum`
*/
function getVotingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) {
// make sure block number is not in the past (not the finalized block)
require(_blockNum < block.number, "not yet determined"); // Compound msg
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// if voting power history for the account provided is empty
if(history.length == 0) {
// than voting power is zero - return the result
return 0;
}
// check latest voting power history record block number:
// if history was not updated after the block of interest
if(history[history.length - 1].blockNumber <= _blockNum) {
// we're done - return last voting power record
return getVotingPower(_of);
}
// check first voting power history record block number:
// if history was never updated before the block of interest
if(history[0].blockNumber > _blockNum) {
// we're done - voting power at the block num of interest was zero
return 0;
}
// `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending;
// apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that
// `votingPowerHistory[_of][i].blockNumber <= _blockNum`, but in the same time
// `votingPowerHistory[_of][i + 1].blockNumber > _blockNum`
// return the result - voting power found at index `i`
return history[__binaryLookup(_of, _blockNum)].votingPower;
}
/**
* @dev Reads an entire voting power history array for the delegate specified
*
* @param _of delegate to query voting power history for
* @return voting power history array for the delegate of interest
*/
function getVotingPowerHistory(address _of) public view returns(VotingPowerRecord[] memory) {
// return an entire array as memory
return votingPowerHistory[_of];
}
/**
* @dev Returns length of the voting power history array for the delegate specified;
* useful since reading an entire array just to get its length is expensive (gas cost)
*
* @param _of delegate to query voting power history length for
* @return voting power history array length for the delegate of interest
*/
function getVotingPowerHistoryLength(address _of) public view returns(uint256) {
// read array length and return
return votingPowerHistory[_of].length;
}
/**
* @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to`
*
* @dev Accepts zero value address to delegate voting power to, effectively
* removing the delegate in that case
*
* @param _to address to delegate voting power to
*/
function delegate(address _to) public {
// verify delegations are enabled
require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled");
// delegate call to `__delegate`
__delegate(msg.sender, _to);
}
/**
* @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to`
*
* @dev Accepts zero value address to delegate voting power to, effectively
* removing the delegate in that case
*
* @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing,
* see https://eips.ethereum.org/EIPS/eip-712
*
* @param _to address to delegate voting power to
* @param _nonce nonce used to construct the signature, and used to validate it;
* nonce is increased by one after successful signature validation and vote delegation
* @param _exp signature expiration time
* @param v the recovery byte of the signature
* @param r half of the ECDSA signature pair
* @param s half of the ECDSA signature pair
*/
function delegateWithSig(address _to, uint256 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public {
// verify delegations on behalf are enabled
require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled");
// build the EIP-712 contract domain separator
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this)));
// build the EIP-712 hashStruct of the delegation message
bytes32 hashStruct = keccak256(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp));
// calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message)
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, hashStruct));
// recover the address who signed the message with v, r, s
address signer = ecrecover(digest, v, r, s);
// perform message integrity and security validations
require(signer != address(0), "invalid signature"); // Compound msg
require(_nonce == nonces[signer], "invalid nonce"); // Compound msg
require(block.timestamp < _exp, "signature expired"); // Compound msg
// update the nonce for that particular signer to avoid replay attack
nonces[signer]++;
// delegate call to `__delegate` - execute the logic required
__delegate(signer, _to);
}
/**
* @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to`
* @dev Writes to `votingDelegates` and `votingPowerHistory` mappings
*
* @param _from delegator who delegates his voting power
* @param _to delegate who receives the voting power
*/
function __delegate(address _from, address _to) private {
// read current delegate to be replaced by a new one
address _fromDelegate = votingDelegates[_from];
// read current voting power (it is equal to token balance)
uint256 _value = tokenBalances[_from];
// reassign voting delegate to `_to`
votingDelegates[_from] = _to;
// update voting power for `_fromDelegate` and `_to`
__moveVotingPower(_fromDelegate, _to, _value);
// emit an event
emit DelegateChanged(_from, _fromDelegate, _to);
}
/**
* @dev Auxiliary function to move voting power `_value`
* from delegate `_from` to the delegate `_to`
*
* @dev Doesn't have any effect if `_from == _to`, or if `_value == 0`
*
* @param _from delegate to move voting power from
* @param _to delegate to move voting power to
* @param _value voting power to move from `_from` to `_to`
*/
function __moveVotingPower(address _from, address _to, uint256 _value) private {
// if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`)
if(_from == _to || _value == 0) {
// return silently with no action
return;
}
// if source address is not zero - decrease its voting power
if(_from != address(0)) {
// read current source address voting power
uint256 _fromVal = getVotingPower(_from);
// calculate decreased voting power
// underflow is not possible by design:
// voting power is limited by token balance which is checked by the callee
uint256 _toVal = _fromVal - _value;
// update source voting power from `_fromVal` to `_toVal`
__updateVotingPower(_from, _fromVal, _toVal);
}
// if destination address is not zero - increase its voting power
if(_to != address(0)) {
// read current destination address voting power
uint256 _fromVal = getVotingPower(_to);
// calculate increased voting power
// overflow is not possible by design:
// max token supply limits the cumulative voting power
uint256 _toVal = _fromVal + _value;
// update destination voting power from `_fromVal` to `_toVal`
__updateVotingPower(_to, _fromVal, _toVal);
}
}
/**
* @dev Auxiliary function to update voting power of the delegate `_of`
* from value `_fromVal` to value `_toVal`
*
* @param _of delegate to update its voting power
* @param _fromVal old voting power of the delegate
* @param _toVal new voting power of the delegate
*/
function __updateVotingPower(address _of, uint256 _fromVal, uint256 _toVal) private {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_of];
// if there is an existing voting power value stored for current block
if(history.length != 0 && history[history.length - 1].blockNumber == block.number) {
// update voting power which is already stored in the current block
history[history.length - 1].votingPower = uint192(_toVal);
}
// otherwise - if there is no value stored for current block
else {
// add new element into array representing the value for current block
history.push(VotingPowerRecord(uint64(block.number), uint192(_toVal)));
}
// emit an event
emit VotingPowerChanged(_of, _fromVal, _toVal);
}
/**
* @dev Auxiliary function to lookup an element in a sorted (asc) array of elements
*
* @dev This function finds the closest element in an array to the value
* of interest (not exceeding that value) and returns its index within an array
*
* @dev An array to search in is `votingPowerHistory[_to][i].blockNumber`,
* it is sorted in ascending order (blockNumber increases)
*
* @param _to an address of the delegate to get an array for
* @param n value of interest to look for
* @return an index of the closest element in an array to the value
* of interest (not exceeding that value)
*/
function __binaryLookup(address _to, uint256 n) private view returns(uint256) {
// get a link to an array of voting power history records for an address specified
VotingPowerRecord[] storage history = votingPowerHistory[_to];
// left bound of the search interval, originally start of the array
uint256 i = 0;
// right bound of the search interval, originally end of the array
uint256 j = history.length - 1;
// the iteration process narrows down the bounds by
// splitting the interval in a half oce per each iteration
while(j > i) {
// get an index in the middle of the interval [i, j]
uint256 k = j - (j - i) / 2;
// read an element to compare it with the value of interest
VotingPowerRecord memory cp = history[k];
// if we've got a strict equal - we're lucky and done
if(cp.blockNumber == n) {
// just return the result - index `k`
return k;
}
// if the value of interest is bigger - move left bound to the middle
else if (cp.blockNumber < n) {
// move left bound `i` to the middle position `k`
i = k;
}
// otherwise, when the value of interest is smaller - move right bound to the middle
else {
// move right bound `j` to the middle position `k - 1`:
// element at position `k` is bigger and cannot be the result
j = k - 1;
}
}
// reaching that point means no exact match found
// since we're interested in the element which is not bigger than the
// element of interest, we return the lower bound `i`
return i;
}
}
// ===== End: DAO Support (Compound-like voting delegation) =====
/**
* @title Illuvium Aware
*
* @notice Helper smart contract to be inherited by other smart contracts requiring to
* be linked to verified IlluviumERC20 instance and performing some basic tasks on it
*
* @author Basil Gorin
*/
abstract contract IlluviumAware is ILinkedToILV {
/// @dev Link to ILV ERC20 Token IlluviumERC20 instance
address public immutable override ilv;
/**
* @dev Creates IlluviumAware instance, requiring to supply deployed IlluviumERC20 instance address
*
* @param _ilv deployed IlluviumERC20 instance address
*/
constructor(address _ilv) {
// verify ILV address is set and is correct
require(_ilv != address(0), "ILV address not set");
require(IlluviumERC20(_ilv).TOKEN_UID() == 0x83ecb176af7c4f35a45ff0018282e3a05a1018065da866182df12285866f5a2c, "unexpected TOKEN_UID");
// write ILV address
ilv = _ilv;
}
/**
* @dev Executes IlluviumERC20.safeTransferFrom(address(this), _to, _value, "")
* on the bound IlluviumERC20 instance
*
* @dev Reentrancy safe due to the IlluviumERC20 design
*/
function transferIlv(address _to, uint256 _value) internal {
// just delegate call to the target
transferIlvFrom(address(this), _to, _value);
}
/**
* @dev Executes IlluviumERC20.transferFrom(_from, _to, _value)
* on the bound IlluviumERC20 instance
*
* @dev Reentrancy safe due to the IlluviumERC20 design
*/
function transferIlvFrom(address _from, address _to, uint256 _value) internal {
// just delegate call to the target
IlluviumERC20(ilv).transferFrom(_from, _to, _value);
}
/**
* @dev Executes IlluviumERC20.mint(_to, _values)
* on the bound IlluviumERC20 instance
*
* @dev Reentrancy safe due to the IlluviumERC20 design
*/
function mintIlv(address _to, uint256 _value) internal {
// just delegate call to the target
IlluviumERC20(ilv).mint(_to, _value);
}
}
/**
* @title Illuvium Pool Base
*
* @notice An abstract contract containing common logic for any pool,
* be it a flash pool (temporary pool like SNX) or a core pool (permanent pool like ILV/ETH or ILV pool)
*
* @dev Deployment and initialization.
* Any pool deployed must be bound to the deployed pool factory (IlluviumPoolFactory)
* Additionally, 3 token instance addresses must be defined on deployment:
* - ILV token address
* - sILV token address, used to mint sILV rewards
* - pool token address, it can be ILV token address, ILV/ETH pair address, and others
*
* @dev Pool weight defines the fraction of the yield current pool receives among the other pools,
* pool factory is responsible for the weight synchronization between the pools.
* @dev The weight is logically 10% for ILV pool and 90% for ILV/ETH pool.
* Since Solidity doesn't support fractions the weight is defined by the division of
* pool weight by total pools weight (sum of all registered pools within the factory)
* @dev For ILV Pool we use 100 as weight and for ILV/ETH pool - 900.
*
* @author Pedro Bergamini, reviewed by Basil Gorin
*/
abstract contract IlluviumPoolBase is IPool, IlluviumAware, ReentrancyGuard {
/// @dev Data structure representing token holder using a pool
struct User {
// @dev Total staked amount
uint256 tokenAmount;
// @dev Total weight
uint256 totalWeight;
// @dev Auxiliary variable for yield calculation
uint256 subYieldRewards;
// @dev Auxiliary variable for vault rewards calculation
uint256 subVaultRewards;
// @dev An array of holder's deposits
Deposit[] deposits;
}
/// @dev Token holder storage, maps token holder address to their data record
mapping(address => User) public users;
/// @dev Link to sILV ERC20 Token EscrowedIlluviumERC20 instance
address public immutable override silv;
/// @dev Link to the pool factory IlluviumPoolFactory instance
IlluviumPoolFactory public immutable factory;
/// @dev Link to the pool token instance, for example ILV or ILV/ETH pair
address public immutable override poolToken;
/// @dev Pool weight, 100 for ILV pool or 900 for ILV/ETH
uint32 public override weight;
/// @dev Block number of the last yield distribution event
uint64 public override lastYieldDistribution;
/// @dev Used to calculate yield rewards
/// @dev This value is different from "reward per token" used in locked pool
/// @dev Note: stakes are different in duration and "weight" reflects that
uint256 public override yieldRewardsPerWeight;
/// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking
uint256 public override usersLockingWeight;
/**
* @dev Stake weight is proportional to deposit amount and time locked, precisely
* "deposit amount wei multiplied by (fraction of the year locked plus one)"
* @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1],
* weight is stored multiplied by 1e6 constant, as an integer
* @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6
* @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and
* weight is a deposit amount multiplied by 2 * 1e6
*/
uint256 internal constant WEIGHT_MULTIPLIER = 1e6;
/**
* @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one,
* we use simplified calculation and use the following constant instead previos one
*/
uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER;
/**
* @dev Rewards per weight are stored multiplied by 1e12, as integers.
*/
uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e12;
/**
* @dev Fired in _stake() and stake()
*
* @param _by an address which performed an operation, usually token holder
* @param _from token holder address, the tokens will be returned to that address
* @param amount amount of tokens staked
*/
event Staked(address indexed _by, address indexed _from, uint256 amount);
/**
* @dev Fired in _updateStakeLock() and updateStakeLock()
*
* @param _by an address which performed an operation
* @param depositId updated deposit ID
* @param lockedFrom deposit locked from value
* @param lockedUntil updated deposit locked until value
*/
event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil);
/**
* @dev Fired in _unstake() and unstake()
*
* @param _by an address which performed an operation, usually token holder
* @param _to an address which received the unstaked tokens, usually token holder
* @param amount amount of tokens unstaked
*/
event Unstaked(address indexed _by, address indexed _to, uint256 amount);
/**
* @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.)
*
* @param _by an address which performed an operation
* @param yieldRewardsPerWeight updated yield rewards per weight value
* @param lastYieldDistribution usually, current block number
*/
event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint64 lastYieldDistribution);
/**
* @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.)
*
* @param _by an address which performed an operation
* @param _to an address which claimed the yield reward
* @param sIlv flag indicating if reward was paid (minted) in sILV
* @param amount amount of yield paid
*/
event YieldClaimed(address indexed _by, address indexed _to, bool sIlv, uint256 amount);
/**
* @dev Fired in setWeight()
*
* @param _by an address which performed an operation, always a factory
* @param _fromVal old pool weight value
* @param _toVal new pool weight value
*/
event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal);
/**
* @dev Overridden in sub-contracts to construct the pool
*
* @param _ilv ILV ERC20 Token IlluviumERC20 address
* @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address
* @param _factory Pool factory IlluviumPoolFactory instance/address
* @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair
* @param _initBlock initial block used to calculate the rewards
* note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing
* @param _weight number representing a weight of the pool, actual weight fraction
* is calculated as that number divided by the total pools weight and doesn't exceed one
*/
constructor(
address _ilv,
address _silv,
IlluviumPoolFactory _factory,
address _poolToken,
uint64 _initBlock,
uint32 _weight
) IlluviumAware(_ilv) {
// verify the inputs are set
require(_silv != address(0), "sILV address not set");
require(address(_factory) != address(0), "ILV Pool fct address not set");
require(_poolToken != address(0), "pool token address not set");
require(_initBlock > 0, "init block not set");
require(_weight > 0, "pool weight not set");
// verify sILV instance supplied
require(
EscrowedIlluviumERC20(_silv).TOKEN_UID() ==
0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62,
"unexpected sILV TOKEN_UID"
);
// verify IlluviumPoolFactory instance supplied
require(
_factory.FACTORY_UID() == 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7,
"unexpected FACTORY_UID"
);
// save the inputs into internal state variables
silv = _silv;
factory = _factory;
poolToken = _poolToken;
weight = _weight;
// init the dependent internal state variables
lastYieldDistribution = _initBlock;
}
/**
* @notice Calculates current yield rewards value available for address specified
*
* @param _staker an address to calculate yield rewards value for
* @return calculated yield reward value for the given address
*/
function pendingYieldRewards(address _staker) external view override returns (uint256) {
// `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight`
uint256 newYieldRewardsPerWeight;
// if smart contract state was not updated recently, `yieldRewardsPerWeight` value
// is outdated and we need to recalculate it in order to calculate pending rewards correctly
if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) {
uint256 endBlock = factory.endBlock();
uint256 multiplier =
blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution;
uint256 ilvRewards = (multiplier * weight * factory.ilvPerBlock()) / factory.totalWeight();
// recalculated value for `yieldRewardsPerWeight`
newYieldRewardsPerWeight = rewardToWeight(ilvRewards, usersLockingWeight) + yieldRewardsPerWeight;
} else {
// if smart contract state is up to date, we don't recalculate
newYieldRewardsPerWeight = yieldRewardsPerWeight;
}
// based on the rewards per weight value, calculate pending rewards;
User memory user = users[_staker];
uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards;
return pending;
}
/**
* @notice Returns total staked token balance for the given address
*
* @param _user an address to query balance for
* @return total staked token balance
*/
function balanceOf(address _user) external view override returns (uint256) {
// read specified user token amount and return
return users[_user].tokenAmount;
}
/**
* @notice Returns information on the given deposit for the given address
*
* @dev See getDepositsLength
*
* @param _user an address to query deposit for
* @param _depositId zero-indexed deposit ID for the address specified
* @return deposit info as Deposit structure
*/
function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) {
// read deposit at specified index and return
return users[_user].deposits[_depositId];
}
/**
* @notice Returns number of deposits for the given address. Allows iteration over deposits.
*
* @dev See getDeposit
*
* @param _user an address to query deposit length for
* @return number of deposits for the given address
*/
function getDepositsLength(address _user) external view override returns (uint256) {
// read deposits array length and return
return users[_user].deposits.length;
}
/**
* @notice Stakes specified amount of tokens for the specified amount of time,
* and pays pending yield rewards if any
*
* @dev Requires amount to stake to be greater than zero
*
* @param _amount amount of tokens to stake
* @param _lockUntil stake period as unix timestamp; zero means no locking
* @param _useSILV a flag indicating if previous reward to be paid as sILV
*/
function stake(
uint256 _amount,
uint64 _lockUntil,
bool _useSILV
) external override {
// delegate call to an internal function
_stake(msg.sender, _amount, _lockUntil, _useSILV, false);
}
/**
* @notice Unstakes specified amount of tokens, and pays pending yield rewards if any
*
* @dev Requires amount to unstake to be greater than zero
*
* @param _depositId deposit ID to unstake from, zero-indexed
* @param _amount amount of tokens to unstake
* @param _useSILV a flag indicating if reward to be paid as sILV
*/
function unstake(
uint256 _depositId,
uint256 _amount,
bool _useSILV
) external override {
// delegate call to an internal function
_unstake(msg.sender, _depositId, _amount, _useSILV);
}
/**
* @notice Extends locking period for a given deposit
*
* @dev Requires new lockedUntil value to be:
* higher than the current one, and
* in the future, but
* no more than 1 year in the future
*
* @param depositId updated deposit ID
* @param lockedUntil updated deposit locked until value
* @param useSILV used for _processRewards check if it should use ILV or sILV
*/
function updateStakeLock(
uint256 depositId,
uint64 lockedUntil,
bool useSILV
) external {
// sync and call processRewards
_sync();
_processRewards(msg.sender, useSILV, false);
// delegate call to an internal function
_updateStakeLock(msg.sender, depositId, lockedUntil);
}
/**
* @notice Service function to synchronize pool state with current time
*
* @dev Can be executed by anyone at any time, but has an effect only when
* at least one block passes between synchronizations
* @dev Executed internally when staking, unstaking, processing rewards in order
* for calculations to be correct and to reflect state progress of the contract
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*/
function sync() external override {
// delegate call to an internal function
_sync();
}
/**
* @notice Service function to calculate and pay pending yield rewards to the sender
*
* @dev Can be executed by anyone at any time, but has an effect only when
* executed by deposit holder and when at least one block passes from the
* previous reward processing
* @dev Executed internally when staking and unstaking, executes sync() under the hood
* before making further calculations and payouts
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*
* @param _useSILV flag indicating whether to mint sILV token as a reward or not;
* when set to true - sILV reward is minted immediately and sent to sender,
* when set to false - new ILV reward deposit gets created if pool is an ILV pool
* (poolToken is ILV token), or new pool deposit gets created together with sILV minted
* when pool is not an ILV pool (poolToken is not an ILV token)
*/
function processRewards(bool _useSILV) external virtual override {
// delegate call to an internal function
_processRewards(msg.sender, _useSILV, true);
}
/**
* @dev Executed by the factory to modify pool weight; the factory is expected
* to keep track of the total pools weight when updating
*
* @dev Set weight to zero to disable the pool
*
* @param _weight new weight to set for the pool
*/
function setWeight(uint32 _weight) external override {
// verify function is executed by the factory
require(msg.sender == address(factory), "access denied");
// emit an event logging old and new weight values
emit PoolWeightUpdated(msg.sender, weight, _weight);
// set the new weight value
weight = _weight;
}
/**
* @dev Similar to public pendingYieldRewards, but performs calculations based on
* current smart contract state only, not taking into account any additional
* time/blocks which might have passed
*
* @param _staker an address to calculate yield rewards value for
* @return pending calculated yield reward value for the given address
*/
function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) {
// read user data structure into memory
User memory user = users[_staker];
// and perform the calculation using the values read
return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards;
}
/**
* @dev Used internally, mostly by children implementations, see stake()
*
* @param _staker an address which stakes tokens and which will receive them back
* @param _amount amount of tokens to stake
* @param _lockUntil stake period as unix timestamp; zero means no locking
* @param _useSILV a flag indicating if previous reward to be paid as sILV
* @param _isYield a flag indicating if that stake is created to store yield reward
* from the previously unstaked stake
*/
function _stake(
address _staker,
uint256 _amount,
uint64 _lockUntil,
bool _useSILV,
bool _isYield
) internal virtual {
// validate the inputs
require(_amount > 0, "zero amount");
require(
_lockUntil == 0 || (_lockUntil > now256() && _lockUntil - now256() <= 365 days),
"invalid lock interval"
);
// update smart contract state
_sync();
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// process current pending rewards if any
if (user.tokenAmount > 0) {
_processRewards(_staker, _useSILV, false);
}
// in most of the cases added amount `addedAmount` is simply `_amount`
// however for deflationary tokens this can be different
// read the current balance
uint256 previousBalance = IERC20(poolToken).balanceOf(address(this));
// transfer `_amount`; note: some tokens may get burnt here
transferPoolTokenFrom(address(msg.sender), address(this), _amount);
// read new balance, usually this is just the difference `previousBalance - _amount`
uint256 newBalance = IERC20(poolToken).balanceOf(address(this));
// calculate real amount taking into account deflation
uint256 addedAmount = newBalance - previousBalance;
// set the `lockFrom` and `lockUntil` taking into account that
// zero value for `_lockUntil` means "no locking" and leads to zero values
// for both `lockFrom` and `lockUntil`
uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0;
uint64 lockUntil = _lockUntil;
// stake weight formula rewards for locking
uint256 stakeWeight =
(((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount;
// makes sure stakeWeight is valid
assert(stakeWeight > 0);
// create and save the deposit (append it to deposits array)
Deposit memory deposit =
Deposit({
tokenAmount: addedAmount,
weight: stakeWeight,
lockedFrom: lockFrom,
lockedUntil: lockUntil,
isYield: _isYield
});
// deposit ID is an index of the deposit in `deposits` array
user.deposits.push(deposit);
// update user record
user.tokenAmount += addedAmount;
user.totalWeight += stakeWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
// update global variable
usersLockingWeight += stakeWeight;
// emit an event
emit Staked(msg.sender, _staker, _amount);
}
/**
* @dev Used internally, mostly by children implementations, see unstake()
*
* @param _staker an address which unstakes tokens (which previously staked them)
* @param _depositId deposit ID to unstake from, zero-indexed
* @param _amount amount of tokens to unstake
* @param _useSILV a flag indicating if reward to be paid as sILV
*/
function _unstake(
address _staker,
uint256 _depositId,
uint256 _amount,
bool _useSILV
) internal virtual {
// verify an amount is set
require(_amount > 0, "zero amount");
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// get a link to the corresponding deposit, we may write to it later
Deposit storage stakeDeposit = user.deposits[_depositId];
// deposit structure may get deleted, so we save isYield flag to be able to use it
bool isYield = stakeDeposit.isYield;
// verify available balance
// if staker address ot deposit doesn't exist this check will fail as well
require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake");
// update smart contract state
_sync();
// and process current pending rewards if any
_processRewards(_staker, _useSILV, false);
// recalculate deposit weight
uint256 previousWeight = stakeDeposit.weight;
uint256 newWeight =
(((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) /
365 days +
WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount);
// update the deposit, or delete it if its depleted
if (stakeDeposit.tokenAmount - _amount == 0) {
delete user.deposits[_depositId];
} else {
stakeDeposit.tokenAmount -= _amount;
stakeDeposit.weight = newWeight;
}
// update user record
user.tokenAmount -= _amount;
user.totalWeight = user.totalWeight - previousWeight + newWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
// update global variable
usersLockingWeight = usersLockingWeight - previousWeight + newWeight;
// if the deposit was created by the pool itself as a yield reward
if (isYield) {
// mint the yield via the factory
factory.mintYieldTo(msg.sender, _amount);
} else {
// otherwise just return tokens back to holder
transferPoolToken(msg.sender, _amount);
}
// emit an event
emit Unstaked(msg.sender, _staker, _amount);
}
/**
* @dev Used internally, mostly by children implementations, see sync()
*
* @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`),
* updates factory state via `updateILVPerBlock`
*/
function _sync() internal virtual {
// update ILV per block value in factory if required
if (factory.shouldUpdateRatio()) {
factory.updateILVPerBlock();
}
// check bound conditions and if these are not met -
// exit silently, without emitting an event
uint256 endBlock = factory.endBlock();
if (lastYieldDistribution >= endBlock) {
return;
}
if (blockNumber() <= lastYieldDistribution) {
return;
}
// if locking weight is zero - update only `lastYieldDistribution` and exit
if (usersLockingWeight == 0) {
lastYieldDistribution = uint64(blockNumber());
return;
}
// to calculate the reward we need to know how many blocks passed, and reward per block
uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber();
uint256 blocksPassed = currentBlock - lastYieldDistribution;
uint256 ilvPerBlock = factory.ilvPerBlock();
// calculate the reward
uint256 ilvReward = (blocksPassed * ilvPerBlock * weight) / factory.totalWeight();
// update rewards per weight and `lastYieldDistribution`
yieldRewardsPerWeight += rewardToWeight(ilvReward, usersLockingWeight);
lastYieldDistribution = uint64(currentBlock);
// emit an event
emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution);
}
/**
* @dev Used internally, mostly by children implementations, see processRewards()
*
* @param _staker an address which receives the reward (which has staked some tokens earlier)
* @param _useSILV flag indicating whether to mint sILV token as a reward or not, see processRewards()
* @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false
* @return pendingYield the rewards calculated and optionally re-staked
*/
function _processRewards(
address _staker,
bool _useSILV,
bool _withUpdate
) internal virtual returns (uint256 pendingYield) {
// update smart contract state if required
if (_withUpdate) {
_sync();
}
// calculate pending yield rewards, this value will be returned
pendingYield = _pendingYieldRewards(_staker);
// if pending yield is zero - just return silently
if (pendingYield == 0) return 0;
// get link to a user data structure, we will write into it later
User storage user = users[_staker];
// if sILV is requested
if (_useSILV) {
// - mint sILV
mintSIlv(_staker, pendingYield);
} else if (poolToken == ilv) {
// calculate pending yield weight,
// 2e6 is the bonus weight when staking for 1 year
uint256 depositWeight = pendingYield * YEAR_STAKE_WEIGHT_MULTIPLIER;
// if the pool is ILV Pool - create new ILV deposit
// and save it - push it into deposits array
Deposit memory newDeposit =
Deposit({
tokenAmount: pendingYield,
lockedFrom: uint64(now256()),
lockedUntil: uint64(now256() + 365 days), // staking yield for 1 year
weight: depositWeight,
isYield: true
});
user.deposits.push(newDeposit);
// update user record
user.tokenAmount += pendingYield;
user.totalWeight += depositWeight;
// update global variable
usersLockingWeight += depositWeight;
} else {
// for other pools - stake as pool
address ilvPool = factory.getPoolAddress(ilv);
ICorePool(ilvPool).stakeAsPool(_staker, pendingYield);
}
// update users's record for `subYieldRewards` if requested
if (_withUpdate) {
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
}
// emit an event
emit YieldClaimed(msg.sender, _staker, _useSILV, pendingYield);
}
/**
* @dev See updateStakeLock()
*
* @param _staker an address to update stake lock
* @param _depositId updated deposit ID
* @param _lockedUntil updated deposit locked until value
*/
function _updateStakeLock(
address _staker,
uint256 _depositId,
uint64 _lockedUntil
) internal {
// validate the input time
require(_lockedUntil > now256(), "lock should be in the future");
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// get a link to the corresponding deposit, we may write to it later
Deposit storage stakeDeposit = user.deposits[_depositId];
// validate the input against deposit structure
require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock");
// verify locked from and locked until values
if (stakeDeposit.lockedFrom == 0) {
require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days");
stakeDeposit.lockedFrom = uint64(now256());
} else {
require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days");
}
// update locked until value, calculate new weight
stakeDeposit.lockedUntil = _lockedUntil;
uint256 newWeight =
(((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) /
365 days +
WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount;
// save previous weight
uint256 previousWeight = stakeDeposit.weight;
// update weight
stakeDeposit.weight = newWeight;
// update user total weight and global locking weight
user.totalWeight = user.totalWeight - previousWeight + newWeight;
usersLockingWeight = usersLockingWeight - previousWeight + newWeight;
// emit an event
emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil);
}
/**
* @dev Converts stake weight (not to be mixed with the pool weight) to
* ILV reward value, applying the 10^12 division on weight
*
* @param _weight stake weight
* @param rewardPerWeight ILV reward per weight
* @return reward value normalized to 10^12
*/
function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) {
// apply the formula and return
return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER;
}
/**
* @dev Converts reward ILV value to stake weight (not to be mixed with the pool weight),
* applying the 10^12 multiplication on the reward
* - OR -
* @dev Converts reward ILV value to reward/weight if stake weight is supplied as second
* function parameter instead of reward/weight
*
* @param reward yield reward
* @param rewardPerWeight reward/weight (or stake weight)
* @return stake weight (or reward/weight)
*/
function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) {
// apply the reverse formula and return
return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight;
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override block number in helper test smart contracts
*
* @return `block.number` in mainnet, custom values in testnets (if overridden)
*/
function blockNumber() public view virtual returns (uint256) {
// return current block number
return block.number;
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override time in helper test smart contracts
*
* @return `block.timestamp` in mainnet, custom values in testnets (if overridden)
*/
function now256() public view virtual returns (uint256) {
// return current block timestamp
return block.timestamp;
}
/**
* @dev Executes EscrowedIlluviumERC20.mint(_to, _values)
* on the bound EscrowedIlluviumERC20 instance
*
* @dev Reentrancy safe due to the EscrowedIlluviumERC20 design
*/
function mintSIlv(address _to, uint256 _value) private {
// just delegate call to the target
EscrowedIlluviumERC20(silv).mint(_to, _value);
}
/**
* @dev Executes SafeERC20.safeTransfer on a pool token
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*/
function transferPoolToken(address _to, uint256 _value) internal nonReentrant {
// just delegate call to the target
SafeERC20.safeTransfer(IERC20(poolToken), _to, _value);
}
/**
* @dev Executes SafeERC20.safeTransferFrom on a pool token
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*/
function transferPoolTokenFrom(
address _from,
address _to,
uint256 _value
) internal nonReentrant {
// just delegate call to the target
SafeERC20.safeTransferFrom(IERC20(poolToken), _from, _to, _value);
}
}
/**
* @title Illuvium Core Pool
*
* @notice Core pools represent permanent pools like ILV or ILV/ETH Pair pool,
* core pools allow staking for arbitrary periods of time up to 1 year
*
* @dev See IlluviumPoolBase for more details
*
* @author Pedro Bergamini, reviewed by Basil Gorin
*/
contract IlluviumCorePool is IlluviumPoolBase {
/// @dev Flag indicating pool type, false means "core pool"
bool public constant override isFlashPool = false;
/// @dev Link to deployed IlluviumVault instance
address public vault;
/// @dev Used to calculate vault rewards
/// @dev This value is different from "reward per token" used in locked pool
/// @dev Note: stakes are different in duration and "weight" reflects that
uint256 public vaultRewardsPerWeight;
/// @dev Pool tokens value available in the pool;
/// pool token examples are ILV (ILV core pool) or ILV/ETH pair (LP core pool)
/// @dev For LP core pool this value doesnt' count for ILV tokens received as Vault rewards
/// while for ILV core pool it does count for such tokens as well
uint256 public poolTokenReserve;
/**
* @dev Fired in receiveVaultRewards()
*
* @param _by an address that sent the rewards, always a vault
* @param amount amount of tokens received
*/
event VaultRewardsReceived(address indexed _by, uint256 amount);
/**
* @dev Fired in _processVaultRewards() and dependent functions, like processRewards()
*
* @param _by an address which executed the function
* @param _to an address which received a reward
* @param amount amount of reward received
*/
event VaultRewardsClaimed(address indexed _by, address indexed _to, uint256 amount);
/**
* @dev Fired in setVault()
*
* @param _by an address which executed the function, always a factory owner
*/
event VaultUpdated(address indexed _by, address _fromVal, address _toVal);
/**
* @dev Creates/deploys an instance of the core pool
*
* @param _ilv ILV ERC20 Token IlluviumERC20 address
* @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address
* @param _factory Pool factory IlluviumPoolFactory instance/address
* @param _poolToken token the pool operates on, for example ILV or ILV/ETH pair
* @param _initBlock initial block used to calculate the rewards
* @param _weight number representing a weight of the pool, actual weight fraction
* is calculated as that number divided by the total pools weight and doesn't exceed one
*/
constructor(
address _ilv,
address _silv,
IlluviumPoolFactory _factory,
address _poolToken,
uint64 _initBlock,
uint32 _weight
) IlluviumPoolBase(_ilv, _silv, _factory, _poolToken, _initBlock, _weight) {}
/**
* @notice Calculates current vault rewards value available for address specified
*
* @dev Performs calculations based on current smart contract state only,
* not taking into account any additional time/blocks which might have passed
*
* @param _staker an address to calculate vault rewards value for
* @return pending calculated vault reward value for the given address
*/
function pendingVaultRewards(address _staker) public view returns (uint256 pending) {
User memory user = users[_staker];
return weightToReward(user.totalWeight, vaultRewardsPerWeight) - user.subVaultRewards;
}
/**
* @dev Executed only by the factory owner to Set the vault
*
* @param _vault an address of deployed IlluviumVault instance
*/
function setVault(address _vault) external {
// verify function is executed by the factory owner
require(factory.owner() == msg.sender, "access denied");
// verify input is set
require(_vault != address(0), "zero input");
// emit an event
emit VaultUpdated(msg.sender, vault, _vault);
// update vault address
vault = _vault;
}
/**
* @dev Executed by the vault to transfer vault rewards ILV from the vault
* into the pool
*
* @dev This function is executed only for ILV core pools
*
* @param _rewardsAmount amount of ILV rewards to transfer into the pool
*/
function receiveVaultRewards(uint256 _rewardsAmount) external {
require(msg.sender == vault, "access denied");
// return silently if there is no reward to receive
if (_rewardsAmount == 0) {
return;
}
require(usersLockingWeight > 0, "zero locking weight");
transferIlvFrom(msg.sender, address(this), _rewardsAmount);
vaultRewardsPerWeight += rewardToWeight(_rewardsAmount, usersLockingWeight);
// update `poolTokenReserve` only if this is a ILV Core Pool
if (poolToken == ilv) {
poolTokenReserve += _rewardsAmount;
}
emit VaultRewardsReceived(msg.sender, _rewardsAmount);
}
/**
* @notice Service function to calculate and pay pending vault and yield rewards to the sender
*
* @dev Internally executes similar function `_processRewards` from the parent smart contract
* to calculate and pay yield rewards; adds vault rewards processing
*
* @dev Can be executed by anyone at any time, but has an effect only when
* executed by deposit holder and when at least one block passes from the
* previous reward processing
* @dev Executed internally when "staking as a pool" (`stakeAsPool`)
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*
* @dev _useSILV flag has a context of yield rewards only
*
* @param _useSILV flag indicating whether to mint sILV token as a reward or not;
* when set to true - sILV reward is minted immediately and sent to sender,
* when set to false - new ILV reward deposit gets created if pool is an ILV pool
* (poolToken is ILV token), or new pool deposit gets created together with sILV minted
* when pool is not an ILV pool (poolToken is not an ILV token)
*/
function processRewards(bool _useSILV) external override {
_processRewards(msg.sender, _useSILV, true);
}
/**
* @dev Executed internally by the pool itself (from the parent `IlluviumPoolBase` smart contract)
* as part of yield rewards processing logic (`IlluviumPoolBase._processRewards` function)
* @dev Executed when _useSILV is false and pool is not an ILV pool - see `IlluviumPoolBase._processRewards`
*
* @param _staker an address which stakes (the yield reward)
* @param _amount amount to be staked (yield reward amount)
*/
function stakeAsPool(address _staker, uint256 _amount) external {
require(factory.poolExists(msg.sender), "access denied");
_sync();
User storage user = users[_staker];
if (user.tokenAmount > 0) {
_processRewards(_staker, true, false);
}
uint256 depositWeight = _amount * YEAR_STAKE_WEIGHT_MULTIPLIER;
Deposit memory newDeposit =
Deposit({
tokenAmount: _amount,
lockedFrom: uint64(now256()),
lockedUntil: uint64(now256() + 365 days),
weight: depositWeight,
isYield: true
});
user.tokenAmount += _amount;
user.totalWeight += depositWeight;
user.deposits.push(newDeposit);
usersLockingWeight += depositWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
// update `poolTokenReserve` only if this is a LP Core Pool (stakeAsPool can be executed only for LP pool)
poolTokenReserve += _amount;
}
/**
* @inheritdoc IlluviumPoolBase
*
* @dev Additionally to the parent smart contract, updates vault rewards of the holder,
* and updates (increases) pool token reserve (pool tokens value available in the pool)
*/
function _stake(
address _staker,
uint256 _amount,
uint64 _lockedUntil,
bool _useSILV,
bool _isYield
) internal override {
super._stake(_staker, _amount, _lockedUntil, _useSILV, _isYield);
User storage user = users[_staker];
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
poolTokenReserve += _amount;
}
/**
* @inheritdoc IlluviumPoolBase
*
* @dev Additionally to the parent smart contract, updates vault rewards of the holder,
* and updates (decreases) pool token reserve (pool tokens value available in the pool)
*/
function _unstake(
address _staker,
uint256 _depositId,
uint256 _amount,
bool _useSILV
) internal override {
User storage user = users[_staker];
Deposit memory stakeDeposit = user.deposits[_depositId];
require(stakeDeposit.lockedFrom == 0 || now256() > stakeDeposit.lockedUntil, "deposit not yet unlocked");
poolTokenReserve -= _amount;
super._unstake(_staker, _depositId, _amount, _useSILV);
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
}
/**
* @inheritdoc IlluviumPoolBase
*
* @dev Additionally to the parent smart contract, processes vault rewards of the holder,
* and for ILV pool updates (increases) pool token reserve (pool tokens value available in the pool)
*/
function _processRewards(
address _staker,
bool _useSILV,
bool _withUpdate
) internal override returns (uint256 pendingYield) {
_processVaultRewards(_staker);
pendingYield = super._processRewards(_staker, _useSILV, _withUpdate);
// update `poolTokenReserve` only if this is a ILV Core Pool
if (poolToken == ilv && !_useSILV) {
poolTokenReserve += pendingYield;
}
}
/**
* @dev Used internally to process vault rewards for the staker
*
* @param _staker address of the user (staker) to process rewards for
*/
function _processVaultRewards(address _staker) private {
User storage user = users[_staker];
uint256 pendingVaultClaim = pendingVaultRewards(_staker);
if (pendingVaultClaim == 0) return;
// read ILV token balance of the pool via standard ERC20 interface
uint256 ilvBalance = IERC20(ilv).balanceOf(address(this));
require(ilvBalance >= pendingVaultClaim, "contract ILV balance too low");
// update `poolTokenReserve` only if this is a ILV Core Pool
if (poolToken == ilv) {
// protects against rounding errors
poolTokenReserve -= pendingVaultClaim > poolTokenReserve ? poolTokenReserve : pendingVaultClaim;
}
user.subVaultRewards = weightToReward(user.totalWeight, vaultRewardsPerWeight);
// transfer fails if pool ILV balance is not enough - which is a desired behavior
transferIlv(_staker, pendingVaultClaim);
emit VaultRewardsClaimed(msg.sender, _staker, pendingVaultClaim);
}
}
/**
* @title Illuvium Pool Factory
*
* @notice ILV Pool Factory manages Illuvium Yield farming pools, provides a single
* public interface to access the pools, provides an interface for the pools
* to mint yield rewards, access pool-related info, update weights, etc.
*
* @notice The factory is authorized (via its owner) to register new pools, change weights
* of the existing pools, removing the pools (by changing their weights to zero)
*
* @dev The factory requires ROLE_TOKEN_CREATOR permission on the ILV token to mint yield
* (see `mintYieldTo` function)
*
* @author Pedro Bergamini, reviewed by Basil Gorin
*/
contract IlluviumPoolFactory is Ownable, IlluviumAware {
/**
* @dev Smart contract unique identifier, a random number
* @dev Should be regenerated each time smart contact source code is changed
* and changes smart contract itself is to be redeployed
* @dev Generated using https://www.random.org/bytes/
*/
uint256 public constant FACTORY_UID = 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7;
/// @dev Auxiliary data structure used only in getPoolData() view function
struct PoolData {
// @dev pool token address (like ILV)
address poolToken;
// @dev pool address (like deployed core pool instance)
address poolAddress;
// @dev pool weight (200 for ILV pools, 800 for ILV/ETH pools - set during deployment)
uint32 weight;
// @dev flash pool flag
bool isFlashPool;
}
/**
* @dev ILV/block determines yield farming reward base
* used by the yield pools controlled by the factory
*/
uint192 public ilvPerBlock;
/**
* @dev The yield is distributed proportionally to pool weights;
* total weight is here to help in determining the proportion
*/
uint32 public totalWeight;
/**
* @dev ILV/block decreases by 3% every blocks/update (set to 91252 blocks during deployment);
* an update is triggered by executing `updateILVPerBlock` public function
*/
uint32 public immutable blocksPerUpdate;
/**
* @dev End block is the last block when ILV/block can be decreased;
* it is implied that yield farming stops after that block
*/
uint32 public endBlock;
/**
* @dev Each time the ILV/block ratio gets updated, the block number
* when the operation has occurred gets recorded into `lastRatioUpdate`
* @dev This block number is then used to check if blocks/update `blocksPerUpdate`
* has passed when decreasing yield reward by 3%
*/
uint32 public lastRatioUpdate;
/// @dev sILV token address is used to create ILV core pool(s)
address public immutable silv;
/// @dev Maps pool token address (like ILV) -> pool address (like core pool instance)
mapping(address => address) public pools;
/// @dev Keeps track of registered pool addresses, maps pool address -> exists flag
mapping(address => bool) public poolExists;
/**
* @dev Fired in createPool() and registerPool()
*
* @param _by an address which executed an action
* @param poolToken pool token address (like ILV)
* @param poolAddress deployed pool instance address
* @param weight pool weight
* @param isFlashPool flag indicating if pool is a flash pool
*/
event PoolRegistered(
address indexed _by,
address indexed poolToken,
address indexed poolAddress,
uint64 weight,
bool isFlashPool
);
/**
* @dev Fired in changePoolWeight()
*
* @param _by an address which executed an action
* @param poolAddress deployed pool instance address
* @param weight new pool weight
*/
event WeightUpdated(address indexed _by, address indexed poolAddress, uint32 weight);
/**
* @dev Fired in updateILVPerBlock()
*
* @param _by an address which executed an action
* @param newIlvPerBlock new ILV/block value
*/
event IlvRatioUpdated(address indexed _by, uint256 newIlvPerBlock);
/**
* @dev Creates/deploys a factory instance
*
* @param _ilv ILV ERC20 token address
* @param _silv sILV ERC20 token address
* @param _ilvPerBlock initial ILV/block value for rewards
* @param _blocksPerUpdate how frequently the rewards gets updated (decreased by 3%), blocks
* @param _initBlock block number to measure _blocksPerUpdate from
* @param _endBlock block number when farming stops and rewards cannot be updated anymore
*/
constructor(
address _ilv,
address _silv,
uint192 _ilvPerBlock,
uint32 _blocksPerUpdate,
uint32 _initBlock,
uint32 _endBlock
) IlluviumAware(_ilv) {
// verify the inputs are set
require(_silv != address(0), "sILV address not set");
require(_ilvPerBlock > 0, "ILV/block not set");
require(_blocksPerUpdate > 0, "blocks/update not set");
require(_initBlock > 0, "init block not set");
require(_endBlock > _initBlock, "invalid end block: must be greater than init block");
// verify sILV instance supplied
require(
EscrowedIlluviumERC20(_silv).TOKEN_UID() ==
0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62,
"unexpected sILV TOKEN_UID"
);
// save the inputs into internal state variables
silv = _silv;
ilvPerBlock = _ilvPerBlock;
blocksPerUpdate = _blocksPerUpdate;
lastRatioUpdate = _initBlock;
endBlock = _endBlock;
}
/**
* @notice Given a pool token retrieves corresponding pool address
*
* @dev A shortcut for `pools` mapping
*
* @param poolToken pool token address (like ILV) to query pool address for
* @return pool address for the token specified
*/
function getPoolAddress(address poolToken) external view returns (address) {
// read the mapping and return
return pools[poolToken];
}
/**
* @notice Reads pool information for the pool defined by its pool token address,
* designed to simplify integration with the front ends
*
* @param _poolToken pool token address to query pool information for
* @return pool information packed in a PoolData struct
*/
function getPoolData(address _poolToken) public view returns (PoolData memory) {
// get the pool address from the mapping
address poolAddr = pools[_poolToken];
// throw if there is no pool registered for the token specified
require(poolAddr != address(0), "pool not found");
// read pool information from the pool smart contract
// via the pool interface (IPool)
address poolToken = IPool(poolAddr).poolToken();
bool isFlashPool = IPool(poolAddr).isFlashPool();
uint32 weight = IPool(poolAddr).weight();
// create the in-memory structure and return it
return PoolData({ poolToken: poolToken, poolAddress: poolAddr, weight: weight, isFlashPool: isFlashPool });
}
/**
* @dev Verifies if `blocksPerUpdate` has passed since last ILV/block
* ratio update and if ILV/block reward can be decreased by 3%
*
* @return true if enough time has passed and `updateILVPerBlock` can be executed
*/
function shouldUpdateRatio() public view returns (bool) {
// if yield farming period has ended
if (blockNumber() > endBlock) {
// ILV/block reward cannot be updated anymore
return false;
}
// check if blocks/update (91252 blocks) have passed since last update
return blockNumber() >= lastRatioUpdate + blocksPerUpdate;
}
/**
* @dev Creates a core pool (IlluviumCorePool) and registers it within the factory
*
* @dev Can be executed by the pool factory owner only
*
* @param poolToken pool token address (like ILV, or ILV/ETH pair)
* @param initBlock init block to be used for the pool created
* @param weight weight of the pool to be created
*/
function createPool(
address poolToken,
uint64 initBlock,
uint32 weight
) external virtual onlyOwner {
// create/deploy new core pool instance
IPool pool = new IlluviumCorePool(ilv, silv, this, poolToken, initBlock, weight);
// register it within a factory
registerPool(address(pool));
}
/**
* @dev Registers an already deployed pool instance within the factory
*
* @dev Can be executed by the pool factory owner only
*
* @param poolAddr address of the already deployed pool instance
*/
function registerPool(address poolAddr) public onlyOwner {
// read pool information from the pool smart contract
// via the pool interface (IPool)
address poolToken = IPool(poolAddr).poolToken();
bool isFlashPool = IPool(poolAddr).isFlashPool();
uint32 weight = IPool(poolAddr).weight();
// ensure that the pool is not already registered within the factory
require(pools[poolToken] == address(0), "this pool is already registered");
// create pool structure, register it within the factory
pools[poolToken] = poolAddr;
poolExists[poolAddr] = true;
// update total pool weight of the factory
totalWeight += weight;
// emit an event
emit PoolRegistered(msg.sender, poolToken, poolAddr, weight, isFlashPool);
}
/**
* @notice Decreases ILV/block reward by 3%, can be executed
* no more than once per `blocksPerUpdate` blocks
*/
function updateILVPerBlock() external {
// checks if ratio can be updated i.e. if blocks/update (91252 blocks) have passed
require(shouldUpdateRatio(), "too frequent");
// decreases ILV/block reward by 3%
ilvPerBlock = (ilvPerBlock * 97) / 100;
// set current block as the last ratio update block
lastRatioUpdate = uint32(blockNumber());
// emit an event
emit IlvRatioUpdated(msg.sender, ilvPerBlock);
}
/**
* @dev Mints ILV tokens; executed by ILV Pool only
*
* @dev Requires factory to have ROLE_TOKEN_CREATOR permission
* on the ILV ERC20 token instance
*
* @param _to an address to mint tokens to
* @param _amount amount of ILV tokens to mint
*/
function mintYieldTo(address _to, uint256 _amount) external {
// verify that sender is a pool registered withing the factory
require(poolExists[msg.sender], "access denied");
// mint ILV tokens as required
mintIlv(_to, _amount);
}
/**
* @dev Changes the weight of the pool;
* executed by the pool itself or by the factory owner
*
* @param poolAddr address of the pool to change weight for
* @param weight new weight value to set to
*/
function changePoolWeight(address poolAddr, uint32 weight) external {
// verify function is executed either by factory owner or by the pool itself
require(msg.sender == owner() || poolExists[msg.sender]);
// recalculate total weight
totalWeight = totalWeight + weight - IPool(poolAddr).weight();
// set the new pool weight
IPool(poolAddr).setWeight(weight);
// emit an event
emit WeightUpdated(msg.sender, poolAddr, weight);
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override block number in helper test smart contracts
*
* @return `block.number` in mainnet, custom values in testnets (if overridden)
*/
function blockNumber() public view virtual returns (uint256) {
// return current block number
return block.number;
}
}
/**
* @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 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.3._
*/
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.3._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
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");
}
}
}
/**
* @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}.
*/
// Copied from Open Zeppelin
contract ERC20 is IERC20 {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @notice Token creator is responsible for creating (minting)
* tokens to an arbitrary address
* @dev Role ROLE_TOKEN_CREATOR allows minting tokens
* (calling `mint` function)
*/
uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, 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(msg.sender, 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, msg.sender, _allowances[sender][msg.sender] - 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(msg.sender, spender, _allowances[msg.sender][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) {
_approve(msg.sender, spender, _allowances[msg.sender][spender] - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender] - amount;
_balances[recipient] = _balances[recipient] + amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply + amount;
_balances[account] = _balances[account] + amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account] - amount;
_totalSupply = _totalSupply - amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
contract EscrowedIlluviumERC20 is ERC20("Escrowed Illuvium", "sILV"), AccessControl {
/**
* @dev Smart contract unique identifier, a random number
* @dev Should be regenerated each time smart contact source code is changed
* and changes smart contract itself is to be redeployed
* @dev Generated using https://www.random.org/bytes/
*/
uint256 public constant TOKEN_UID = 0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62;
/**
* @notice Must be called by ROLE_TOKEN_CREATOR addresses.
*
* @param recipient address to receive the tokens.
* @param amount number of tokens to be minted.
*/
function mint(address recipient, uint256 amount) external {
require(isSenderInRole(ROLE_TOKEN_CREATOR), "insufficient privileges (ROLE_TOKEN_CREATOR required)");
_mint(recipient, amount);
}
/**
* @param amount number of tokens to be burned.
*/
function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
}
/**
* @title Flash Pool Base
*
* @notice An abstract contract containing logic for a new Flash Pool version.
* It fixes the REWARD_PER_WEIGHT_MULTIPLIER constant to allow bigger supply
* tokens flash pools.
*
* @dev Deployment and initialization.
* Any pool deployed must be bound to the deployed pool factory (IlluviumPoolFactory)
* Additionally, 3 token instance addresses must be defined on deployment:
* - ILV token address
* - sILV token address, used to mint sILV rewards
* - pool token address, it can be ILV token address, ILV/ETH pair address, and others
*
* @dev Pool weight defines the fraction of the yield current pool receives among the other pools,
* pool factory is responsible for the weight synchronization between the pools.
* @dev The weight is logically 10% for ILV pool and 90% for ILV/ETH pool.
* Since Solidity doesn't support fractions the weight is defined by the division of
* pool weight by total pools weight (sum of all registered pools within the factory)
* @dev For ILV Pool we use 200 as weight and for ILV/ETH pool 800.
*
* @author Pedro Bergamini, reviewed by Basil Gorin
*/
abstract contract FlashPoolBase is IPool, IlluviumAware, ReentrancyGuard {
/// @dev Data structure representing token holder using a pool
struct User {
// @dev Total staked amount
uint256 tokenAmount;
// @dev Total weight
uint256 totalWeight;
// @dev Auxiliary variable for yield calculation
uint256 subYieldRewards;
// @dev Auxiliary variable for vault rewards calculation
uint256 subVaultRewards;
// @dev An array of holder's deposits
Deposit[] deposits;
}
/// @dev Token holder storage, maps token holder address to their data record
mapping(address => User) public users;
/// @dev Link to sILV ERC20 Token EscrowedIlluviumERC20 instance
address public immutable override silv;
/// @dev Link to the pool factory IlluviumPoolFactory instance
IlluviumPoolFactory public immutable factory;
/// @dev Link to the internal token instance, for example SNX or XYZ
address public immutable internalToken;
/// @dev Pool weight, 100 for ILV pool or 900 for ILV/ETH
uint32 public override weight;
/// @dev Block number of the last yield distribution event
uint64 public override lastYieldDistribution;
/// @dev Used to calculate yield rewards
/// @dev This value is different from "reward per token" used in locked pool
/// @dev Note: stakes are different in duration and "weight" reflects that
uint256 public override yieldRewardsPerWeight;
/// @dev Used to calculate yield rewards, keeps track of the tokens weight locked in staking
uint256 public override usersLockingWeight;
/**
* @dev Stake weight is proportional to deposit amount and time locked, precisely
* "deposit amount wei multiplied by (fraction of the year locked plus one)"
* @dev To avoid significant precision loss due to multiplication by "fraction of the year" [0, 1],
* weight is stored multiplied by 1e6 constant, as an integer
* @dev Corner case 1: if time locked is zero, weight is deposit amount multiplied by 1e6
* @dev Corner case 2: if time locked is one year, fraction of the year locked is one, and
* weight is a deposit amount multiplied by 2 * 1e6
*/
uint256 internal constant WEIGHT_MULTIPLIER = 1e6;
/**
* @dev When we know beforehand that staking is done for a year, and fraction of the year locked is one,
* we use simplified calculation and use the following constant instead previos one
*/
uint256 internal constant YEAR_STAKE_WEIGHT_MULTIPLIER = 2 * WEIGHT_MULTIPLIER;
/**
* @dev Rewards per weight are stored multiplied by 1e12, as integers.
*/
uint256 internal constant REWARD_PER_WEIGHT_MULTIPLIER = 1e18;
/**
* @dev Fired in _stake() and stake()
*
* @param _by an address which performed an operation, usually token holder
* @param _from token holder address, the tokens will be returned to that address
* @param amount amount of tokens staked
*/
event Staked(address indexed _by, address indexed _from, uint256 amount);
/**
* @dev Fired in _updateStakeLock() and updateStakeLock()
*
* @param _by an address which performed an operation
* @param depositId updated deposit ID
* @param lockedFrom deposit locked from value
* @param lockedUntil updated deposit locked until value
*/
event StakeLockUpdated(address indexed _by, uint256 depositId, uint64 lockedFrom, uint64 lockedUntil);
/**
* @dev Fired in _unstake() and unstake()
*
* @param _by an address which performed an operation, usually token holder
* @param _to an address which received the unstaked tokens, usually token holder
* @param amount amount of tokens unstaked
*/
event Unstaked(address indexed _by, address indexed _to, uint256 amount);
/**
* @dev Fired in _sync(), sync() and dependent functions (stake, unstake, etc.)
*
* @param _by an address which performed an operation
* @param yieldRewardsPerWeight updated yield rewards per weight value
* @param lastYieldDistribution usually, current block number
*/
event Synchronized(address indexed _by, uint256 yieldRewardsPerWeight, uint64 lastYieldDistribution);
/**
* @dev Fired in _processRewards(), processRewards() and dependent functions (stake, unstake, etc.)
*
* @param _by an address which performed an operation
* @param _to an address which claimed the yield reward
* @param sIlv flag indicating if reward was paid (minted) in sILV
* @param amount amount of yield paid
*/
event YieldClaimed(address indexed _by, address indexed _to, bool sIlv, uint256 amount);
/**
* @dev Fired in setWeight()
*
* @param _by an address which performed an operation, always a factory
* @param _fromVal old pool weight value
* @param _toVal new pool weight value
*/
event PoolWeightUpdated(address indexed _by, uint32 _fromVal, uint32 _toVal);
/**
* @dev Overridden in sub-contracts to construct the pool
*
* @param _ilv ILV ERC20 Token IlluviumERC20 address
* @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address
* @param _factory Pool factory IlluviumPoolFactory instance/address
* @param _internalToken token the pool operates on
* @param _initBlock initial block used to calculate the rewards
* note: _initBlock can be set to the future effectively meaning _sync() calls will do nothing
* @param _weight number representing a weight of the pool, actual weight fraction
* is calculated as that number divided by the total pools weight and doesn't exceed one
*/
constructor(
address _ilv,
address _silv,
IlluviumPoolFactory _factory,
address _internalToken,
uint64 _initBlock,
uint32 _weight
) IlluviumAware(_ilv) {
// verify the inputs are set
require(_silv != address(0), "sILV address not set");
require(address(_factory) != address(0), "ILV Pool fct address not set");
require(_internalToken != address(0), "token address not set");
require(_initBlock > 0, "init block not set");
require(_weight > 0, "pool weight not set");
// verify sILV instance supplied
require(
EscrowedIlluviumERC20(_silv).TOKEN_UID() ==
0xac3051b8d4f50966afb632468a4f61483ae6a953b74e387a01ef94316d6b7d62,
"unexpected sILV TOKEN_UID"
);
// verify IlluviumPoolFactory instance supplied
require(
_factory.FACTORY_UID() == 0xc5cfd88c6e4d7e5c8a03c255f03af23c0918d8e82cac196f57466af3fd4a5ec7,
"unexpected FACTORY_UID"
);
// save the inputs into internal state variables
silv = _silv;
factory = _factory;
internalToken = _internalToken;
weight = _weight;
// init the dependent internal state variables
lastYieldDistribution = _initBlock;
}
/**
* @dev Faked link to the pool token instance
*/
function poolToken() external view override returns(address) {
return address(this);
}
/**
* @notice Calculates current yield rewards value available for address specified
*
* @param _staker an address to calculate yield rewards value for
* @return calculated yield reward value for the given address
*/
function pendingYieldRewards(address _staker) external view override returns (uint256) {
// `newYieldRewardsPerWeight` will store stored or recalculated value for `yieldRewardsPerWeight`
uint256 newYieldRewardsPerWeight;
// if smart contract state was not updated recently, `yieldRewardsPerWeight` value
// is outdated and we need to recalculate it in order to calculate pending rewards correctly
if (blockNumber() > lastYieldDistribution && usersLockingWeight != 0) {
uint256 endBlock = factory.endBlock();
uint256 multiplier =
blockNumber() > endBlock ? endBlock - lastYieldDistribution : blockNumber() - lastYieldDistribution;
uint256 ilvRewards = (multiplier * weight * factory.ilvPerBlock()) / factory.totalWeight();
// recalculated value for `yieldRewardsPerWeight`
newYieldRewardsPerWeight = rewardToWeight(ilvRewards, usersLockingWeight) + yieldRewardsPerWeight;
} else {
// if smart contract state is up to date, we don't recalculate
newYieldRewardsPerWeight = yieldRewardsPerWeight;
}
// based on the rewards per weight value, calculate pending rewards;
User memory user = users[_staker];
uint256 pending = weightToReward(user.totalWeight, newYieldRewardsPerWeight) - user.subYieldRewards;
return pending;
}
/**
* @notice Returns total staked token balance for the given address
*
* @param _user an address to query balance for
* @return total staked token balance
*/
function balanceOf(address _user) external view override returns (uint256) {
// read specified user token amount and return
return users[_user].tokenAmount;
}
/**
* @notice Returns information on the given deposit for the given address
*
* @dev See getDepositsLength
*
* @param _user an address to query deposit for
* @param _depositId zero-indexed deposit ID for the address specified
* @return deposit info as Deposit structure
*/
function getDeposit(address _user, uint256 _depositId) external view override returns (Deposit memory) {
// read deposit at specified index and return
return users[_user].deposits[_depositId];
}
/**
* @notice Returns number of deposits for the given address. Allows iteration over deposits.
*
* @dev See getDeposit
*
* @param _user an address to query deposit length for
* @return number of deposits for the given address
*/
function getDepositsLength(address _user) external view override returns (uint256) {
// read deposits array length and return
return users[_user].deposits.length;
}
/**
* @notice Stakes specified amount of tokens for the specified amount of time,
* and pays pending yield rewards if any
*
* @dev Requires amount to stake to be greater than zero
*
* @param _amount amount of tokens to stake
* @param _lockUntil stake period as unix timestamp; zero means no locking
* @param _useSILV a flag indicating if previous reward to be paid as sILV
*/
function stake(
uint256 _amount,
uint64 _lockUntil,
bool _useSILV
) external override {
// delegate call to an internal function
_stake(msg.sender, _amount, _lockUntil, _useSILV, false);
}
/**
* @notice Unstakes specified amount of tokens, and pays pending yield rewards if any
*
* @dev Requires amount to unstake to be greater than zero
*
* @param _depositId deposit ID to unstake from, zero-indexed
* @param _amount amount of tokens to unstake
* @param _useSILV a flag indicating if reward to be paid as sILV
*/
function unstake(
uint256 _depositId,
uint256 _amount,
bool _useSILV
) external override {
// delegate call to an internal function
_unstake(msg.sender, _depositId, _amount, _useSILV);
}
/**
* @notice Extends locking period for a given deposit
*
* @dev Requires new lockedUntil value to be:
* higher than the current one, and
* in the future, but
* no more than 1 year in the future
*
* @param depositId updated deposit ID
* @param lockedUntil updated deposit locked until value
* @param useSILV used for _processRewards check if it should use ILV or sILV
*/
function updateStakeLock(
uint256 depositId,
uint64 lockedUntil,
bool useSILV
) external {
// sync and call processRewards
_sync();
_processRewards(msg.sender, useSILV, false);
// delegate call to an internal function
_updateStakeLock(msg.sender, depositId, lockedUntil);
}
/**
* @notice Service function to synchronize pool state with current time
*
* @dev Can be executed by anyone at any time, but has an effect only when
* at least one block passes between synchronizations
* @dev Executed internally when staking, unstaking, processing rewards in order
* for calculations to be correct and to reflect state progress of the contract
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*/
function sync() external override {
// delegate call to an internal function
_sync();
}
/**
* @notice Service function to calculate and pay pending yield rewards to the sender
*
* @dev Can be executed by anyone at any time, but has an effect only when
* executed by deposit holder and when at least one block passes from the
* previous reward processing
* @dev Executed internally when staking and unstaking, executes sync() under the hood
* before making further calculations and payouts
* @dev When timing conditions are not met (executed too frequently, or after factory
* end block), function doesn't throw and exits silently
*
* @param _useSILV flag indicating whether to mint sILV token as a reward or not;
* when set to true - sILV reward is minted immediately and sent to sender,
* when set to false - new pool deposit gets created together with sILV minted
*/
function processRewards(bool _useSILV) external virtual override {
// delegate call to an internal function
_processRewards(msg.sender, _useSILV, true);
}
/**
* @dev Executed by the factory to modify pool weight; the factory is expected
* to keep track of the total pools weight when updating
*
* @dev Set weight to zero to disable the pool
*
* @param _weight new weight to set for the pool
*/
function setWeight(uint32 _weight) external override {
// verify function is executed by the factory
require(msg.sender == address(factory), "access denied");
// emit an event logging old and new weight values
emit PoolWeightUpdated(msg.sender, weight, _weight);
// set the new weight value
weight = _weight;
}
/**
* @dev Similar to public pendingYieldRewards, but performs calculations based on
* current smart contract state only, not taking into account any additional
* time/blocks which might have passed
*
* @param _staker an address to calculate yield rewards value for
* @return pending calculated yield reward value for the given address
*/
function _pendingYieldRewards(address _staker) internal view returns (uint256 pending) {
// read user data structure into memory
User memory user = users[_staker];
// and perform the calculation using the values read
return weightToReward(user.totalWeight, yieldRewardsPerWeight) - user.subYieldRewards;
}
/**
* @dev Used internally, mostly by children implementations, see stake()
*
* @param _staker an address which stakes tokens and which will receive them back
* @param _amount amount of tokens to stake
* @param _lockUntil stake period as unix timestamp; zero means no locking
* @param _useSILV a flag indicating if previous reward to be paid as sILV
* @param _isYield a flag indicating if that stake is created to store yield reward
* from the previously unstaked stake
*/
function _stake(
address _staker,
uint256 _amount,
uint64 _lockUntil,
bool _useSILV,
bool _isYield
) internal virtual {
// validate the inputs
require(_amount > 0, "zero amount");
require(
_lockUntil == 0 || (_lockUntil > now256() && _lockUntil - now256() <= 365 days),
"invalid lock interval"
);
// update smart contract state
_sync();
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// process current pending rewards if any
if (user.tokenAmount > 0) {
_processRewards(_staker, _useSILV, false);
}
// in most of the cases added amount `addedAmount` is simply `_amount`
// however for deflationary tokens this can be different
// read the current balance
uint256 previousBalance = IERC20(internalToken).balanceOf(address(this));
// transfer `_amount`; note: some tokens may get burnt here
transferPoolTokenFrom(address(msg.sender), address(this), _amount);
// read new balance, usually this is just the difference `previousBalance - _amount`
uint256 newBalance = IERC20(internalToken).balanceOf(address(this));
// calculate real amount taking into account deflation
uint256 addedAmount = newBalance - previousBalance;
// set the `lockFrom` and `lockUntil` taking into account that
// zero value for `_lockUntil` means "no locking" and leads to zero values
// for both `lockFrom` and `lockUntil`
uint64 lockFrom = _lockUntil > 0 ? uint64(now256()) : 0;
uint64 lockUntil = _lockUntil;
// stake weight formula rewards for locking
uint256 stakeWeight =
(((lockUntil - lockFrom) * WEIGHT_MULTIPLIER) / 365 days + WEIGHT_MULTIPLIER) * addedAmount;
// makes sure stakeWeight is valid
assert(stakeWeight > 0);
// create and save the deposit (append it to deposits array)
Deposit memory deposit =
Deposit({
tokenAmount: addedAmount,
weight: stakeWeight,
lockedFrom: lockFrom,
lockedUntil: lockUntil,
isYield: _isYield
});
// deposit ID is an index of the deposit in `deposits` array
user.deposits.push(deposit);
// update user record
user.tokenAmount += addedAmount;
user.totalWeight += stakeWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
// update global variable
usersLockingWeight += stakeWeight;
// emit an event
emit Staked(msg.sender, _staker, _amount);
}
/**
* @dev Used internally, mostly by children implementations, see unstake()
*
* @param _staker an address which unstakes tokens (which previously staked them)
* @param _depositId deposit ID to unstake from, zero-indexed
* @param _amount amount of tokens to unstake
* @param _useSILV a flag indicating if reward to be paid as sILV
*/
function _unstake(
address _staker,
uint256 _depositId,
uint256 _amount,
bool _useSILV
) internal virtual {
// verify an amount is set
require(_amount > 0, "zero amount");
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// get a link to the corresponding deposit, we may write to it later
Deposit storage stakeDeposit = user.deposits[_depositId];
// deposit structure may get deleted, so we save isYield flag to be able to use it
bool isYield = stakeDeposit.isYield;
// verify available balance
// if staker address ot deposit doesn't exist this check will fail as well
require(stakeDeposit.tokenAmount >= _amount, "amount exceeds stake");
// update smart contract state
_sync();
// and process current pending rewards if any
_processRewards(_staker, _useSILV, false);
// recalculate deposit weight
uint256 previousWeight = stakeDeposit.weight;
uint256 newWeight =
(((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) /
365 days +
WEIGHT_MULTIPLIER) * (stakeDeposit.tokenAmount - _amount);
// update the deposit, or delete it if its depleted
if (stakeDeposit.tokenAmount - _amount == 0) {
delete user.deposits[_depositId];
} else {
stakeDeposit.tokenAmount -= _amount;
stakeDeposit.weight = newWeight;
}
// update user record
user.tokenAmount -= _amount;
user.totalWeight = user.totalWeight - previousWeight + newWeight;
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
// update global variable
usersLockingWeight = usersLockingWeight - previousWeight + newWeight;
// if the deposit was created by the pool itself as a yield reward
if (isYield) {
// mint the yield via the factory
factory.mintYieldTo(msg.sender, _amount);
} else {
// otherwise just return tokens back to holder
transferPoolToken(msg.sender, _amount);
}
// emit an event
emit Unstaked(msg.sender, _staker, _amount);
}
/**
* @dev Used internally, mostly by children implementations, see sync()
*
* @dev Updates smart contract state (`yieldRewardsPerWeight`, `lastYieldDistribution`),
* updates factory state via `updateILVPerBlock`
*/
function _sync() internal virtual {
// update ILV per block value in factory if required
if (factory.shouldUpdateRatio()) {
factory.updateILVPerBlock();
}
// check bound conditions and if these are not met -
// exit silently, without emitting an event
uint256 endBlock = factory.endBlock();
if (lastYieldDistribution >= endBlock) {
return;
}
if (blockNumber() <= lastYieldDistribution) {
return;
}
// if locking weight is zero - update only `lastYieldDistribution` and exit
if (usersLockingWeight == 0) {
lastYieldDistribution = uint64(blockNumber());
return;
}
// to calculate the reward we need to know how many blocks passed, and reward per block
uint256 currentBlock = blockNumber() > endBlock ? endBlock : blockNumber();
uint256 blocksPassed = currentBlock - lastYieldDistribution;
uint256 ilvPerBlock = factory.ilvPerBlock();
// calculate the reward
uint256 ilvReward = (blocksPassed * ilvPerBlock * weight) / factory.totalWeight();
// update rewards per weight and `lastYieldDistribution`
yieldRewardsPerWeight += rewardToWeight(ilvReward, usersLockingWeight);
lastYieldDistribution = uint64(currentBlock);
// emit an event
emit Synchronized(msg.sender, yieldRewardsPerWeight, lastYieldDistribution);
}
/**
* @dev Used internally, mostly by children implementations, see processRewards()
*
* @param _staker an address which receives the reward (which has staked some tokens earlier)
* @param _useSILV flag indicating whether to mint sILV token as a reward or not, see processRewards()
* @param _withUpdate flag allowing to disable synchronization (see sync()) if set to false
* @return pendingYield the rewards calculated and optionally re-staked
*/
function _processRewards(
address _staker,
bool _useSILV,
bool _withUpdate
) internal virtual returns (uint256 pendingYield) {
// update smart contract state if required
if (_withUpdate) {
_sync();
}
// calculate pending yield rewards, this value will be returned
pendingYield = _pendingYieldRewards(_staker);
// if pending yield is zero - just return silently
if (pendingYield == 0) return 0;
// get link to a user data structure, we will write into it later
User storage user = users[_staker];
// if sILV is requested
if (_useSILV) {
// - mint sILV
mintSIlv(_staker, pendingYield);
} else {
// for other pools - stake as pool
address ilvPool = factory.getPoolAddress(ilv);
ICorePool(ilvPool).stakeAsPool(_staker, pendingYield);
}
// update users's record for `subYieldRewards` if requested
if (_withUpdate) {
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
}
// emit an event
emit YieldClaimed(msg.sender, _staker, _useSILV, pendingYield);
}
/**
* @dev See updateStakeLock()
*
* @param _staker an address to update stake lock
* @param _depositId updated deposit ID
* @param _lockedUntil updated deposit locked until value
*/
function _updateStakeLock(
address _staker,
uint256 _depositId,
uint64 _lockedUntil
) internal {
// validate the input time
require(_lockedUntil > now256(), "lock should be in the future");
// get a link to user data struct, we will write to it later
User storage user = users[_staker];
// get a link to the corresponding deposit, we may write to it later
Deposit storage stakeDeposit = user.deposits[_depositId];
// validate the input against deposit structure
require(_lockedUntil > stakeDeposit.lockedUntil, "invalid new lock");
// verify locked from and locked until values
if (stakeDeposit.lockedFrom == 0) {
require(_lockedUntil - now256() <= 365 days, "max lock period is 365 days");
stakeDeposit.lockedFrom = uint64(now256());
} else {
require(_lockedUntil - stakeDeposit.lockedFrom <= 365 days, "max lock period is 365 days");
}
// update locked until value, calculate new weight
stakeDeposit.lockedUntil = _lockedUntil;
uint256 newWeight =
(((stakeDeposit.lockedUntil - stakeDeposit.lockedFrom) * WEIGHT_MULTIPLIER) /
365 days +
WEIGHT_MULTIPLIER) * stakeDeposit.tokenAmount;
// save previous weight
uint256 previousWeight = stakeDeposit.weight;
// update weight
stakeDeposit.weight = newWeight;
// update user total weight and global locking weight
user.totalWeight = user.totalWeight - previousWeight + newWeight;
usersLockingWeight = usersLockingWeight - previousWeight + newWeight;
// emit an event
emit StakeLockUpdated(_staker, _depositId, stakeDeposit.lockedFrom, _lockedUntil);
}
/**
* @dev Converts stake weight (not to be mixed with the pool weight) to
* ILV reward value, applying the 10^12 division on weight
*
* @param _weight stake weight
* @param rewardPerWeight ILV reward per weight
* @return reward value normalized to 10^12
*/
function weightToReward(uint256 _weight, uint256 rewardPerWeight) public pure returns (uint256) {
// apply the formula and return
return (_weight * rewardPerWeight) / REWARD_PER_WEIGHT_MULTIPLIER;
}
/**
* @dev Converts reward ILV value to stake weight (not to be mixed with the pool weight),
* applying the 10^12 multiplication on the reward
* - OR -
* @dev Converts reward ILV value to reward/weight if stake weight is supplied as second
* function parameter instead of reward/weight
*
* @param reward yield reward
* @param rewardPerWeight reward/weight (or stake weight)
* @return stake weight (or reward/weight)
*/
function rewardToWeight(uint256 reward, uint256 rewardPerWeight) public pure returns (uint256) {
// apply the reverse formula and return
return (reward * REWARD_PER_WEIGHT_MULTIPLIER) / rewardPerWeight;
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override block number in helper test smart contracts
*
* @return `block.number` in mainnet, custom values in testnets (if overridden)
*/
function blockNumber() public view virtual returns (uint256) {
// return current block number
return block.number;
}
/**
* @dev Testing time-dependent functionality is difficult and the best way of
* doing it is to override time in helper test smart contracts
*
* @return `block.timestamp` in mainnet, custom values in testnets (if overridden)
*/
function now256() public view virtual returns (uint256) {
// return current block timestamp
return block.timestamp;
}
/**
* @dev Executes EscrowedIlluviumERC20.mint(_to, _values)
* on the bound EscrowedIlluviumERC20 instance
*
* @dev Reentrancy safe due to the EscrowedIlluviumERC20 design
*/
function mintSIlv(address _to, uint256 _value) private {
// just delegate call to the target
EscrowedIlluviumERC20(silv).mint(_to, _value);
}
/**
* @dev Executes SafeERC20.safeTransfer on a pool token
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*/
function transferPoolToken(address _to, uint256 _value) internal nonReentrant {
// just delegate call to the target
SafeERC20.safeTransfer(IERC20(internalToken), _to, _value);
}
/**
* @dev Executes SafeERC20.safeTransferFrom on a pool token
*
* @dev Reentrancy safety enforced via `ReentrancyGuard.nonReentrant`
*/
function transferPoolTokenFrom(
address _from,
address _to,
uint256 _value
) internal nonReentrant {
// just delegate call to the target
SafeERC20.safeTransferFrom(IERC20(internalToken), _from, _to, _value);
}
}
/**
* @title Flash Pool V2
*
* @notice Flash pools represent temporary pools like SNX pool.
*
* @notice Flash pools doesn't lock tokens, staked tokens can be unstaked at any time
*
* @dev See FlashPoolBase for more details
*
* @author Pedro Bergamini, reviewed by Basil Gorin
*/
contract FlashPoolV2 is FlashPoolBase {
/// @dev Pool expiration time, the pool considered to be disabled once end block is reached
/// @dev Expired pools don't process any rewards, users are expected to withdraw staked tokens
/// from the flash pools once they expire
uint64 public endBlock;
/// @dev Flag indicating pool type, true means "flash pool"
bool public constant override isFlashPool = true;
/**
* @dev Creates/deploys an instance of the flash pool
*
* @param _ilv ILV ERC20 Token IlluviumERC20 address
* @param _silv sILV ERC20 Token EscrowedIlluviumERC20 address
* @param _factory Pool factory IlluviumPoolFactory instance/address
* @param _internalToken token the pool operates on, for example ILV or ILV/ETH pair
* @param _initBlock initial block used to calculate the rewards
* @param _weight number representing a weight of the pool, actual weight fraction
* is calculated as that number divided by the total pools weight and doesn't exceed one
* @param _endBlock pool expiration time (as block number)
*/
constructor(
address _ilv,
address _silv,
IlluviumPoolFactory _factory,
address _internalToken,
uint64 _initBlock,
uint32 _weight,
uint64 _endBlock
) FlashPoolBase(_ilv, _silv, _factory, _internalToken, _initBlock, _weight) {
// check the inputs which are not checked by the pool base
require(_endBlock > _initBlock, "end block must be higher than init block");
// assign the end block
endBlock = _endBlock;
}
/**
* @notice The function to check pool state. Flash pool is considered "disabled"
* once time reaches its "end block"
*
* @return true if pool is disabled (time has reached end block), false otherwise
*/
function isPoolDisabled() public view returns (bool) {
// verify the pool expiration condition and return the result
return blockNumber() >= endBlock;
}
/**
* @inheritdoc FlashPoolBase
*
* @dev Overrides the _stake() in base by setting the locked until value to 1 year in the future;
* locked until value has only locked weight effect and doesn't do any real token locking
*
* @param _lockedUntil not used, overridden with now + 1 year just to have correct calculation
* of the locking weights
*/
function _stake(
address _staker,
uint256 _amount,
uint64 _lockedUntil,
bool useSILV,
bool isYield
) internal override {
// override the `_lockedUntil` and execute parent
// we set "locked period" to 365 days only to have correct calculation of locking weights,
// the tokens are not really locked since _unstake in the core pool doesn't check the "locked period"
super._stake(_staker, _amount, uint64(now256() + 365 days), useSILV, isYield);
}
/**
* @inheritdoc FlashPoolBase
*
* @dev In addition to regular sync() routine of the base, set the pool weight
* to zero, effectively disabling the pool in the factory
* @dev If the pool is disabled regular sync() routine is ignored
*/
function _sync() internal override {
// if pool is disabled/expired
if (isPoolDisabled()) {
// if weight is not yet set
if (weight != 0) {
// set the pool weight (sets both factory and local values)
factory.changePoolWeight(address(this), 0);
}
// and exit
return;
}
// for enabled pools perform regular sync() routine
super._sync();
}
}
|
Used internally, mostly by children implementations, see processRewards() _staker an address which receives the reward (which has staked some tokens earlier) _useSILV flag indicating whether to mint sILV token as a reward or not, see processRewards() _withUpdate flag allowing to disable synchronization (see sync()) if set to false return pendingYield the rewards calculated and optionally re-staked/ update smart contract state if required if sILV is requested - mint sILV for other pools - stake as pool update users's record for `subYieldRewards` if requested
|
function _processRewards(
address _staker,
bool _useSILV,
bool _withUpdate
) internal virtual returns (uint256 pendingYield) {
if (_withUpdate) {
_sync();
}
if (_useSILV) {
mintSIlv(_staker, pendingYield);
address ilvPool = factory.getPoolAddress(ilv);
ICorePool(ilvPool).stakeAsPool(_staker, pendingYield);
}
if (_withUpdate) {
user.subYieldRewards = weightToReward(user.totalWeight, yieldRewardsPerWeight);
}
}
| 6,185,836
|
./partial_match/1/0xB700cdadaa6b802236F5CF9fe13D2a70A9588350/sources/lib/openzeppelin-contracts-upgradeable/contracts/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol
|
Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. Emits an {Upgraded} event./ Upgrades from old implementations will perform a rollback test. This test requires the new implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing this special case will break upgrade paths from old UUPS implementation to new ones.
|
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
| 2,586,344
|
./partial_match/1/0x26f8bd0C78aEE08777234251eD5Fe2D76C645a31/sources/RibbitToken.sol
|
Withdraw tokens sent by mistake. tokenAddress The address of the token to withdraw
|
function rescueERC20Tokens(address tokenAddress) external onlyOwner {
IERC20(tokenAddress).transfer(
msg.sender,
IERC20(tokenAddress).balanceOf(address(this))
);
}
| 2,790,038
|
./partial_match/1/0xc088f4A4c2E5A99e9B52De108833d9D8b58b2782/sources/PYUSDToken.sol
|
Moves `asmoaugnt` tokens asmoaugnt from acacodunt the asmoaugntcaller's acacodunt to `acacoduntrecipient`./
|
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
| 2,764,480
|
./full_match/1/0xadeC97DDc587F5285528069112b9B09F5aE5D15e/sources/CyberSamurai.sol
|
Returns an array of token IDs owned by `owner`. This function scans the ownership mapping and is O(totalSupply) in complexity. It is meant to be called off-chain. See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into multiple smaller scans if the collection is large enough to cause an out-of-gas error (10K pfp collections should be fine)./
|
function tokensOfOwner(address owner) external view override returns (uint256[] memory) {
unchecked {
uint256 tokenIdsIdx;
address currOwnershipAddr;
uint256 tokenIdsLength = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](tokenIdsLength);
TokenOwnership memory ownership;
for (uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i) {
ownership = _ownershipAt(i);
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx++] = i;
}
}
return tokenIds;
}
}
| 8,365,286
|
//Address: 0xfdfD5dB568f2eCF9b06a16116B9201b0500735B4
//Contract name: VelixIDToken
//Balance: 0 Ether
//Verification Date: 1/30/2018
//Transacion Count: 220
// CODE STARTS HERE
/**
* This smart contract is modified 2017 by Velix.ID to assemble code for creation of VelixIDToken with
* it's unique characteristics.
*
* Licensed under the Apache License, version 2.0
*/
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
pragma solidity ^0.4.18;
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title 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) public 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) public 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 available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract BurnableToken is StandardToken {
address public constant BURN_ADDRESS = 0;
/** How many tokens we burned */
event Burned(address burner, uint burnedAmount);
/**
* Burn extra tokens from a balance.
*
*/
function burn(uint burnAmount) public {
address burner = msg.sender;
balances[burner] = SafeMath.sub(balances[burner], burnAmount);
totalSupply = SafeMath.sub(totalSupply, burnAmount);
Burned(burner, burnAmount);
}
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* Define interface for releasing the token transfer after a successful crowdsale.
*/
contract ReleasableToken is ERC20, Ownable {
/* The finalizer contract that allows unlift the transfer limits on this token */
address public releaseAgent;
/** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/
bool public released = false;
/** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */
mapping (address => bool) public transferAgents;
event CanTransferChecked(bool canTransfer, address indexed from, bool isTransferAgent, bool isReleased);
/**
* Limit token transfer until the crowdsale is over.
*
*/
modifier canTransfer(address _sender) {
CanTransferChecked(released || transferAgents[_sender], _sender, transferAgents[_sender], released);
if (released || transferAgents[_sender]) {revert();}
_;
}
/**
* Set the contract that can call release and make the token transferable.
*
* Design choice. Allow reset the release agent to fix fat finger mistakes.
*/
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
// We don't do interface check here as we might want to a normal wallet address to act as a release agent
releaseAgent = addr;
}
/**
* Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period.
*/
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
transferAgents[addr] = state;
}
/**
* One way function to release the tokens to the wild.
*
* Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached).
*/
function releaseTokenTransfer() public onlyReleaseAgent {
released = true;
}
/** The function can be called only before or after the tokens have been releasesd */
modifier inReleaseState(bool releaseState) {
require(releaseState == released);
_;
}
/** The function can be called only by a whitelisted release agent. */
modifier onlyReleaseAgent() {
require(msg.sender == releaseAgent);
_;
}
function transfer(address _to, uint _value) public returns (bool success) {
// Call StandardToken.transfer()
CanTransferChecked(released || transferAgents[msg.sender], msg.sender, transferAgents[msg.sender], released);
if (released || transferAgents[msg.sender]) {revert();}
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
// Call StandardToken.transferForm()
CanTransferChecked(released || transferAgents[msg.sender], msg.sender, transferAgents[msg.sender], released);
if (released || transferAgents[msg.sender]) {revert();}
return super.transferFrom(_from, _to, _value);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* VelixIDToken
*
* Capped, burnable, and transfer releaseable ERC20 token
* for Velix.ID
*
*/
contract VelixIDToken is ReleasableToken, BurnableToken {
// contract VelixIDToken is ReleasableToken {
using SafeMath for uint256;
/** Name and symbol were updated. */
event UpdatedTokenInformation(string newName, string newSymbol);
string public name;
string public symbol;
uint public decimals;
// mapping(address => uint256) balances;
/**
* Construct the token.
*
* @param _name Token name
* @param _symbol Token symbol
* @param _initialSupply How many tokens we start with
* @param _decimals Number of decimal places
*/
function VelixIDToken(string _name, string _symbol, uint _initialSupply, uint _decimals) public {
// Cannot create a token without supply
require(_initialSupply != 0);
owner = msg.sender;
name = _name;
symbol = _symbol;
totalSupply = _initialSupply;
decimals = _decimals;
// Create initially all balance on owner
balances[owner] = totalSupply;
}
/**
* To update token information at the end.
*
*/
function setTokenInformation(string _name, string _symbol) onlyOwner public {
name = _name;
symbol = _symbol;
UpdatedTokenInformation(name, symbol);
}
function transfer(address _to, uint _value) public returns (bool success) {
// Call StandardToken.transfer()
CanTransferChecked(released || transferAgents[msg.sender], msg.sender, transferAgents[msg.sender], released);
if (released || transferAgents[msg.sender]) {
return super.transfer(_to, _value);
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
// Call StandardToken.transferForm()
CanTransferChecked(released || transferAgents[msg.sender], msg.sender, transferAgents[msg.sender], released);
if (released || transferAgents[msg.sender]) {
return super.transferFrom(_from, _to, _value);
} else {
return false;
}
}
}
|
Call StandardToken.transferForm()
|
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
CanTransferChecked(released || transferAgents[msg.sender], msg.sender, transferAgents[msg.sender], released);
if (released || transferAgents[msg.sender]) {
return super.transferFrom(_from, _to, _value);
return false;
}
}
| 14,052,920
|
./full_match/44787/0x33F8d23a573544a9D80B74c029a3aB392aEDB40A/sources/contracts/StarFarm.sol
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this)).add(pool.extraAmount);
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
starToken.safeTransfer(bonusAddr, starReward.div(10));
pool.accStarPerShare = pool.accStarPerShare.add(starReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 13,250,112
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-Licene-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./libraries/DecimalsConverter.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IShieldMining.sol";
import "./interfaces/ILiquidityRegistry.sol";
import "./interfaces/IPolicyBookAdmin.sol";
import "./interfaces/IPolicyBookFacade.sol";
import "./interfaces/helpers/IPriceFeed.sol";
import "./interfaces/IPolicyBookFabric.sol";
import "./interfaces/IPolicyBookRegistry.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract PolicyBookFacade is IPolicyBookFacade, AbstractDependant, Initializable {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
IPolicyBookAdmin public policyBookAdmin;
ILeveragePortfolio public reinsurancePool;
IPolicyBook public override policyBook;
IShieldMining public shieldMining;
IPolicyBookRegistry public policyBookRegistry;
using SafeMath for uint256;
ILiquidityRegistry public liquidityRegistry;
address public capitalPoolAddress;
address public priceFeed;
// virtual funds deployed by reinsurance pool
uint256 public override VUreinsurnacePool;
// leverage funds deployed by reinsurance pool
uint256 public override LUreinsurnacePool;
// leverage funds deployed by user leverage pool
mapping(address => uint256) public override LUuserLeveragePool;
// total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
uint256 public override totalLeveragedLiquidity;
uint256 public override userleveragedMPL;
uint256 public override reinsurancePoolMPL;
uint256 public override rebalancingThreshold;
bool public override safePricingModel;
mapping(address => uint256) public override userLiquidity;
EnumerableSet.AddressSet internal userLeveragePools;
event DeployLeverageFunds(uint256 _deployedAmount);
modifier onlyCapitalPool() {
require(msg.sender == capitalPoolAddress, "PBFC: only CapitalPool");
_;
}
modifier onlyPolicyBookAdmin() {
require(msg.sender == address(policyBookAdmin), "PBFC: Not a PBA");
_;
}
modifier onlyLeveragePortfolio() {
require(
msg.sender == address(reinsurancePool) ||
policyBookRegistry.isUserLeveragePool(msg.sender),
"PBFC: only LeveragePortfolio"
);
_;
}
modifier onlyPolicyBookRegistry() {
require(msg.sender == address(policyBookRegistry), "PBFC: Not a policy book registry");
_;
}
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 _initialDeposit
) external override initializer {
policyBook = IPolicyBook(pbProxy);
rebalancingThreshold = DEFAULT_REBALANCING_THRESHOLD;
userLiquidity[liquidityProvider] = _initialDeposit;
}
function setDependencies(IContractsRegistry contractsRegistry)
external
override
onlyInjectorOrZero
{
IContractsRegistry _contractsRegistry = IContractsRegistry(contractsRegistry);
capitalPoolAddress = _contractsRegistry.getCapitalPoolContract();
policyBookRegistry = IPolicyBookRegistry(
_contractsRegistry.getPolicyBookRegistryContract()
);
liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract());
policyBookAdmin = IPolicyBookAdmin(_contractsRegistry.getPolicyBookAdminContract());
priceFeed = _contractsRegistry.getPriceFeedContract();
reinsurancePool = ILeveragePortfolio(_contractsRegistry.getReinsurancePoolContract());
shieldMining = IShieldMining(_contractsRegistry.getShieldMiningContract());
}
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber is number of seconds to cover
/// @param _coverTokens is number of tokens to cover
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external override {
_buyPolicy(msg.sender, msg.sender, _epochsNumber, _coverTokens, 0, address(0));
}
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external override {
_buyPolicy(msg.sender, _holder, _epochsNumber, _coverTokens, 0, address(0));
}
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external override {
uint256 _distributorFee = policyBookAdmin.distributorFees(_distributor);
_buyPolicy(
msg.sender,
msg.sender,
_epochsNumber,
_coverTokens,
_distributorFee,
_distributor
);
}
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _holder address user the policy is being "bought for"
/// @param _epochsNumber is number of seconds to cover
/// @param _coverTokens is number of tokens to cover
function buyPolicyFromDistributorFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external override {
uint256 _distributorFee = policyBookAdmin.distributorFees(_distributor);
_buyPolicy(
msg.sender,
_holder,
_epochsNumber,
_coverTokens,
_distributorFee,
_distributor
);
}
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external override {
_addLiquidity(msg.sender, msg.sender, _liquidityAmount, 0);
}
function addLiquidityFromDistributorFor(address _liquidityHolderAddr, uint256 _liquidityAmount)
external
override
{
_addLiquidity(msg.sender, _liquidityHolderAddr, _liquidityAmount, 0);
}
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount)
external
override
{
_addLiquidity(msg.sender, msg.sender, _liquidityAmount, _stakeSTBLAmount);
}
function _addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) internal {
policyBook.addLiquidity(
_liquidityBuyerAddr,
_liquidityHolderAddr,
_liquidityAmount,
_stakeSTBLAmount
);
_reevaluateProvidedLeverageStable(_liquidityAmount);
_updateShieldMining(_liquidityHolderAddr, _liquidityAmount, false);
}
function _buyPolicy(
address _policyBuyerAddr,
address _policyHolderAddr,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) internal {
(uint256 _premium, ) =
policyBook.buyPolicy(
_policyBuyerAddr,
_policyHolderAddr,
_epochsNumber,
_coverTokens,
_distributorFee,
_distributor
);
_reevaluateProvidedLeverageStable(_premium);
}
function _reevaluateProvidedLeverageStable(uint256 newAmount) internal {
if (policyBook.totalLiquidity() > 0 && policyBook.totalCoverTokens() > 0) {
uint256 _newAmountPercentage =
newAmount.mul(PERCENTAGE_100).div(policyBook.totalLiquidity());
if (_newAmountPercentage > rebalancingThreshold) {
_deployLeveragedFunds();
}
} else if (policyBook.totalLiquidity() == 0 || policyBook.totalCoverTokens() == 0) {
// TODO hard rebalancing
}
}
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external override onlyLeveragePortfolio {
if (leveragePool == ILeveragePortfolio.LeveragePortfolio.USERLEVERAGEPOOL) {
LUuserLeveragePool[msg.sender] = deployedAmount;
LUuserLeveragePool[msg.sender] > 0
? userLeveragePools.add(msg.sender)
: userLeveragePools.remove(msg.sender);
} else {
LUreinsurnacePool = deployedAmount;
}
uint256 _LUuserLeveragePool;
if (userLeveragePools.length() > 0) {
_LUuserLeveragePool = LUuserLeveragePool[userLeveragePools.at(0)];
}
totalLeveragedLiquidity = VUreinsurnacePool.add(LUreinsurnacePool).add(
_LUuserLeveragePool
);
emit DeployLeverageFunds(deployedAmount);
}
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount)
external
override
onlyLeveragePortfolio
{
VUreinsurnacePool = deployedAmount;
uint256 _LUuserLeveragePool;
if (userLeveragePools.length() > 0) {
_LUuserLeveragePool = LUuserLeveragePool[userLeveragePools.at(0)];
}
totalLeveragedLiquidity = VUreinsurnacePool.add(LUreinsurnacePool).add(
_LUuserLeveragePool
);
emit DeployLeverageFunds(deployedAmount);
}
function _deployLeveragedFunds() internal {
uint256 _deployedAmount;
uint256 _LUuserLeveragePool;
if (reinsurancePoolMPL > 0) {
_deployedAmount = reinsurancePool.deployVirtualStableToCoveragePools();
VUreinsurnacePool = _deployedAmount;
_deployedAmount = reinsurancePool.deployLeverageStableToCoveragePools(
ILeveragePortfolio.LeveragePortfolio.REINSURANCEPOOL
);
LUreinsurnacePool = _deployedAmount;
}
if (userleveragedMPL > 0) {
address[] memory _userLeverageArr =
policyBookRegistry.listByType(
IPolicyBookFabric.ContractType.VARIOUS,
0,
policyBookRegistry.countByType(IPolicyBookFabric.ContractType.VARIOUS)
);
for (uint256 i = 0; i < _userLeverageArr.length; i++) {
_deployedAmount = ILeveragePortfolio(_userLeverageArr[i])
.deployLeverageStableToCoveragePools(
ILeveragePortfolio.LeveragePortfolio.USERLEVERAGEPOOL
);
LUuserLeveragePool[_userLeverageArr[i]] = _deployedAmount;
LUuserLeveragePool[_userLeverageArr[i]] > 0
? userLeveragePools.add(_userLeverageArr[i])
: userLeveragePools.remove(_userLeverageArr[i]);
_LUuserLeveragePool += LUuserLeveragePool[_userLeverageArr[i]];
}
}
totalLeveragedLiquidity = VUreinsurnacePool.add(LUreinsurnacePool).add(
_LUuserLeveragePool
);
}
function _updateShieldMining(
address liquidityProvider,
uint256 liquidityAmount,
bool isWithdraw
) internal {
// check if SM active
if (shieldMining.getShieldTokenAddress(address(policyBook)) != address(0)) {
uint256 totalSupplyAfterMint = IERC20(address(policyBook)).totalSupply();
shieldMining.updateTotalSupply(
address(policyBook),
totalSupplyAfterMint,
liquidityProvider
);
}
if (isWithdraw) {
userLiquidity[liquidityProvider] -= liquidityAmount;
} else {
userLiquidity[liquidityProvider] += liquidityAmount;
}
}
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external override {
uint256 _withdrawAmount = policyBook.withdrawLiquidity(msg.sender);
_reevaluateProvidedLeverageStable(_withdrawAmount);
_updateShieldMining(msg.sender, _withdrawAmount, true);
}
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL)
external
override
onlyPolicyBookAdmin
{
userleveragedMPL = _userLeverageMPL;
reinsurancePoolMPL = _reinsuranceLeverageMPL;
}
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold)
external
override
onlyPolicyBookAdmin
{
require(_newRebalancingThreshold > 0, "PBF: threshold can not be 0");
rebalancingThreshold = _newRebalancingThreshold;
}
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external override onlyPolicyBookAdmin {
safePricingModel = _safePricingModel;
}
/// @notice fetches all the pools data
/// @return uint256 VUreinsurnacePool
/// @return uint256 LUreinsurnacePool
/// @return uint256 LUleveragePool
/// @return uint256 user leverage pool address
function getPoolsData()
external
view
override
returns (
uint256,
uint256,
uint256,
address
)
{
uint256 _LUuserLeveragePool;
address _userLeverageAddress;
if (userLeveragePools.length() > 0) {
_LUuserLeveragePool = DecimalsConverter.convertFrom18(
LUuserLeveragePool[userLeveragePools.at(0)],
policyBook.stblDecimals()
);
_userLeverageAddress = userLeveragePools.at(0);
}
/// TODO for v2 it is one user leverage pool , so need to figure it out after v2
return (
DecimalsConverter.convertFrom18(VUreinsurnacePool, policyBook.stblDecimals()),
DecimalsConverter.convertFrom18(LUreinsurnacePool, policyBook.stblDecimals()),
_LUuserLeveragePool,
_userLeverageAddress
);
}
// TODO possible sandwich attack or allowance fluctuation
function getClaimApprovalAmount(address user) external view override returns (uint256) {
(uint256 _coverTokens, , , , ) = policyBook.policyHolders(user);
_coverTokens = DecimalsConverter.convertFrom18(
_coverTokens.div(100),
policyBook.stblDecimals()
);
return IPriceFeed(priceFeed).howManyBMIsInUSDT(_coverTokens);
}
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external override {
IPolicyBook.WithdrawalStatus _withdrawlStatus = policyBook.getWithdrawalStatus(msg.sender);
require(
_withdrawlStatus == IPolicyBook.WithdrawalStatus.NONE ||
_withdrawlStatus == IPolicyBook.WithdrawalStatus.EXPIRED,
"PBf: ongoing withdrawl request"
);
policyBook.requestWithdrawal(_tokensToWithdraw, msg.sender);
liquidityRegistry.registerWithdrawl(address(policyBook), msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IClaimingRegistry {
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
/// @notice returns anonymous voting duration
function anonymousVotingDuration(uint256 index) external view returns (uint256);
/// @notice returns the whole voting duration
function votingDuration(uint256 index) external view returns (uint256);
/// @notice returns how many time should pass before anyone could calculate a claim result
function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256);
/// @notice returns true if a user can buy new policy of specified PolicyBook
function canBuyNewPolicy(address buyer, address policyBookAddress)
external
view
returns (bool);
/// @notice submits new PolicyBook claim for the user
function submitClaim(
address user,
address policyBookAddress,
string calldata evidenceURI,
uint256 cover,
bool appeal
) external returns (uint256);
/// @notice returns true if the claim with this index exists
function claimExists(uint256 index) external view returns (bool);
/// @notice returns claim submition time
function claimSubmittedTime(uint256 index) external view returns (uint256);
/// @notice returns claim end time or zero in case it is pending
function claimEndTime(uint256 index) external view returns (uint256);
/// @notice returns true if the claim is anonymously votable
function isClaimAnonymouslyVotable(uint256 index) external view returns (bool);
/// @notice returns true if the claim is exposably votable
function isClaimExposablyVotable(uint256 index) external view returns (bool);
/// @notice returns true if claim is anonymously votable or exposably votable
function isClaimVotable(uint256 index) external view returns (bool);
/// @notice returns true if a claim can be calculated by anyone
function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool);
/// @notice returns true if this claim is pending or awaiting
function isClaimPending(uint256 index) external view returns (bool);
/// @notice returns how many claims the holder has
function countPolicyClaimerClaims(address user) external view returns (uint256);
/// @notice returns how many pending claims are there
function countPendingClaims() external view returns (uint256);
/// @notice returns how many claims are there
function countClaims() external view returns (uint256);
/// @notice returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex)
external
view
returns (uint256);
/// @notice returns pending claim index by its ordinal index
function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns claim index by its ordinal index
function claimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns current active claim index by policybook and claimer
function claimIndex(address claimer, address policyBookAddress)
external
view
returns (uint256);
/// @notice returns true if the claim is appealed
function isClaimAppeal(uint256 index) external view returns (bool);
/// @notice returns current status of a claim
function policyStatus(address claimer, address policyBookAddress)
external
view
returns (ClaimStatus);
/// @notice returns current status of a claim
function claimStatus(uint256 index) external view returns (ClaimStatus);
/// @notice returns the claim owner (claimer)
function claimOwner(uint256 index) external view returns (address);
/// @notice returns the claim PolicyBook
function claimPolicyBook(uint256 index) external view returns (address);
/// @notice returns claim info by its index
function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo);
function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount);
function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256);
/// @notice marks the user's claim as Accepted
function acceptClaim(uint256 index) external;
/// @notice marks the user's claim as Rejected
function rejectClaim(uint256 index) external;
/// @notice Update Image Uri in case it contains material that is ilegal
/// or offensive.
/// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri.
/// @param _claimIndex Claim Index that is going to be updated
/// @param _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityMiningContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ILeveragePortfolio {
enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL}
struct LevFundsFactors {
uint256 netMPL;
uint256 netMPLn;
address policyBookAddr;
// uint256 poolTotalLiquidity;
// uint256 poolUR;
// uint256 minUR;
}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
function deployVirtualStableToCoveragePools() external returns (uint256);
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner
/// @param threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 threshold) external;
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a_ProtocolConstant uint256 A protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
/// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max)
/// @param poolUR uint256 utitilization ratio for a coverage pool
/// @return uint256 M facotr
//function calcM(uint256 poolUR) external returns (uint256);
/// @return uint256 the amount of vStable stored in the pool
function totalLiquidity() external view returns (uint256);
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityRegistry {
struct LiquidityInfo {
address policyBookAddr;
uint256 lockedAmount;
uint256 availableAmount;
uint256 bmiXRatio; // multiply availableAmount by this num to get stable coin
}
struct WithdrawalRequestInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableLiquidity;
uint256 readyToWithdrawDate;
uint256 endWithdrawDate;
}
struct WithdrawalSetInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableSTBLAmount;
}
function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external;
function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external;
function getPolicyBooksArrLength(address _userAddr) external view returns (uint256);
function getPolicyBooksArr(address _userAddr)
external
view
returns (address[] memory _resultArr);
function getLiquidityInfos(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (LiquidityInfo[] memory _resultArr);
function getWithdrawalRequests(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr);
function getWithdrawalSet(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr);
function registerWithdrawl(address _policyBook, address _users) external;
function getAllPendingWithdrawalRequestsAmount()
external
returns (uint256 _totalWithdrawlAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
function policyHolders(address _holder)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function policyBookFacade() external view returns (IPolicyBookFacade);
function setPolicyBookFacade(address _policyBookFacade) external;
function EPOCH_DURATION() external view returns (uint256);
function stblDecimals() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function whitelisted() external view returns (bool);
function epochStartTime() external view returns (uint256);
// @TODO: should we let DAO to change contract address?
/// @notice Returns address of contract this PolicyBook covers, access: ANY
/// @return _contract is address of covered contract
function insuranceContractAddress() external view returns (address _contract);
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function totalLiquidity() external view returns (uint256);
function totalCoverTokens() external view returns (uint256);
// /// @notice return MPL for user leverage pool
// function userleveragedMPL() external view returns (uint256);
// /// @notice return MPL for reinsurance pool
// function reinsurancePoolMPL() external view returns (uint256);
// function bmiRewardMultiplier() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function whitelist(bool _whitelisted) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
/// @notice submits new appeal claim of the policy book
function submitAppealAndInitializeVoting(string calldata evidenceURI) external;
/// @notice updates info on claim acceptance
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external;
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
/// @notice view function to get precise policy price
/// @param _epochsNumber is number of epochs to cover
/// @param _coverTokens is number of tokens to cover
/// @param _buyer address of the user who buy the policy
/// @return totalSeconds is number of seconds to cover
/// @return totalPrice is the policy price which will pay by the buyer
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _buyer
)
external
view
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
);
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _buyer who is transferring funds
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external returns (uint256, uint256);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
/// @param _liquidityHolderAddr is address of address to assign cover
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityBuyerAddr address the one that transfer funds
/// @param _liquidityHolderAddr address the one that owns liquidity
/// @param _liquidityAmount uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external;
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity(address sender) external returns (uint256);
function getAPY() external view returns (uint256);
/// @notice Getting user stats, access: ANY
function userStats(address _user) external view returns (PolicyHolder memory);
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max token amount that a user can buy
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is a type of insured contract
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IPolicyBookAdmin {
function getUpgrader() external view returns (address);
function getImplementationOfPolicyBook(address policyBookAddress) external returns (address);
function getImplementationOfPolicyBookFacade(address policyBookFacadeAddress)
external
returns (address);
function getCurrentPolicyBooksImplementation() external view returns (address);
function getCurrentPolicyBooksFacadeImplementation() external view returns (address);
function getCurrentUserLeverageImplementation() external view returns (address);
/// @notice It blacklists or whitelists a PolicyBook. Only whitelisted PolicyBooks can
/// receive stakes and funds
/// @param policyBookAddress PolicyBook address that will be whitelisted or blacklisted
/// @param whitelisted true to whitelist or false to blacklist a PolicyBook
function whitelist(address policyBookAddress, bool whitelisted) external;
/// @notice Whitelist distributor address. Commission fee is 2-5% of the Premium
/// It comes from the Protocol’s fee part
/// @dev If commission fee is 5%, so _distributorFee = 5
/// @param _distributor distributor address that will receive funds
/// @param _distributorFee distributor fee amount
function whitelistDistributor(address _distributor, uint256 _distributorFee) external;
/// @notice Removes a distributor address from the distributor whitelist
/// @param _distributor distributor address that will be blacklist
function blacklistDistributor(address _distributor) external;
/// @notice Distributor commission fee is 2-5% of the Premium
/// It comes from the Protocol’s fee part
/// @dev If max commission fee is 5%, so _distributorFeeCap = 5. Default value is 5
/// @param _distributor address of the distributor
/// @return true if address is a whitelisted distributor
function isWhitelistedDistributor(address _distributor) external view returns (bool);
/// @notice Distributor commission fee is 2-5% of the Premium
/// It comes from the Protocol’s fee part
/// @dev If max commission fee is 5%, so _distributorFeeCap = 5. Default value is 5
/// @param _distributor address of the distributor
/// @return distributor fee value. It is distributor commission
function distributorFees(address _distributor) external view returns (uint256);
/// @notice Used to get a list of whitelisted distributors
/// @dev If max commission fee is 5%, so _distributorFeeCap = 5. Default value is 5
/// @return _distributors a list containing distritubors addresses
/// @return _distributorsFees a list containing distritubors fees
function listDistributors(uint256 offset, uint256 limit)
external
view
returns (address[] memory _distributors, uint256[] memory _distributorsFees);
/// @notice Returns number of whitelisted distributors, access: ANY
function countDistributors() external view returns (uint256);
/// @notice sets the policybookFacade mpls values
/// @param _facadeAddress address of the policybook facade
/// @param _userLeverageMPL uint256 value of the user leverage mpl;
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage mpl
function setPolicyBookFacadeMPLs(
address _facadeAddress,
uint256 _userLeverageMPL,
uint256 _reinsuranceLeverageMPL
) external;
/// @notice sets the policybookFacade mpls values
/// @param _facadeAddress address of the policybook facade
/// @param _newRebalancingThreshold uint256 value of the reinsurance leverage mpl
function setPolicyBookFacadeRebalancingThreshold(
address _facadeAddress,
uint256 _newRebalancingThreshold
) external;
/// @notice sets the policybookFacade mpls values
/// @param _facadeAddress address of the policybook facade
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setPolicyBookFacadeSafePricingModel(address _facadeAddress, bool _safePricingModel)
external;
function setLeveragePortfolioRebalancingThreshold(
address _LeveragePoolAddress,
uint256 _newRebalancingThreshold
) external;
function setLeveragePortfolioProtocolConstant(
address _LeveragePoolAddress,
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
function setUserLeverageMaxCapacities(address _userLeverageAddress, uint256 _maxCapacities)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IPolicyBook.sol";
import "./ILeveragePortfolio.sol";
interface IPolicyBookFacade {
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external;
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external;
function policyBook() external view returns (IPolicyBook);
function userLiquidity(address account) external view returns (uint256);
/// @notice virtual funds deployed by reinsurance pool
function VUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by reinsurance pool
function LUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by user leverage pool
function LUuserLeveragePool(address userLeveragePool) external view returns (uint256);
/// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
function totalLeveragedLiquidity() external view returns (uint256);
function userleveragedMPL() external view returns (uint256);
function reinsurancePoolMPL() external view returns (uint256);
function rebalancingThreshold() external view returns (uint256);
function safePricingModel() external view returns (bool);
/// @notice policyBookFacade initializer
/// @param pbProxy polciybook address upgreadable cotnract.
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 initialDeposit
) external;
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @param _buyer who is buying the coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributorFor(
address _buyer,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _user the one taht add liquidity
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
/// @notice fetches all the pools data
/// @return uint256 VUreinsurnacePool
/// @return uint256 LUreinsurnacePool
/// @return uint256 LUleveragePool
/// @return uint256 user leverage pool address
function getPoolsData()
external
view
returns (
uint256,
uint256,
uint256,
address
);
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external;
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external;
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold) external;
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external;
/// @notice returns how many BMI tokens needs to approve in order to submit a claim
function getClaimApprovalAmount(address user) external view returns (uint256);
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IPolicyBookRegistry {
struct PolicyBookStats {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 maxCapacity;
uint256 totalSTBLLiquidity;
uint256 totalLeveragedLiquidity;
uint256 stakedSTBL;
uint256 APY;
uint256 annualInsuranceCost;
uint256 bmiXRatio;
bool whitelisted;
}
function policyBooksByInsuredAddress(address insuredContract) external view returns (address);
function policyBookFacades(address facadeAddress) external view returns (address);
/// @notice Adds PolicyBook to registry, access: PolicyFabric
function add(
address insuredContract,
IPolicyBookFabric.ContractType contractType,
address policyBook,
address facadeAddress
) external;
function whitelist(address policyBookAddress, bool whitelisted) external;
/// @notice returns required allowances for the policybooks
function getPoliciesPrices(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external view returns (uint256[] memory _durations, uint256[] memory _allowances);
/// @notice Buys a batch of policies
function buyPolicyBatch(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external;
/// @notice Checks if provided address is a PolicyBook
function isPolicyBook(address policyBook) external view returns (bool);
/// @notice Checks if provided address is a policyBookFacade
function isPolicyBookFacade(address _facadeAddress) external view returns (bool);
/// @notice Checks if provided address is a user leverage pool
function isUserLeveragePool(address policyBookAddress) external view returns (bool);
/// @notice Returns number of registered PolicyBooks with certain contract type
function countByType(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
/// @notice Returns number of registered PolicyBooks, access: ANY
function count() external view returns (uint256);
function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
function countWhitelisted() external view returns (uint256);
/// @notice Listing registered PolicyBooks with certain contract type, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type
function listByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses
function list(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
function listByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
function listWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY
function listWithStatsByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Listing registered PolicyBooks with stats, access: ANY
function listWithStats(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Getting stats from policy books, access: ANY
/// @param policyBooks is list of PolicyBooks addresses
function stats(address[] calldata policyBooks)
external
view
returns (PolicyBookStats[] memory _stats);
/// @notice Return existing Policy Book contract, access: ANY
/// @param insuredContract is contract address to lookup for created IPolicyBook
function policyBookFor(address insuredContract) external view returns (address);
/// @notice Getting stats from policy books, access: ANY
/// @param insuredContracts is list of insuredContracts in registry
function statsByInsuredContracts(address[] calldata insuredContracts)
external
view
returns (PolicyBookStats[] memory _stats);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IShieldMining {
struct ShieldMiningInfo {
IERC20 rewardsToken;
uint8 decimals;
uint256 rewardPerBlock;
uint256 lastUpdateBlock;
uint256 lastBlockBeforePause;
uint256 rewardPerTokenStored;
uint256 rewardTokensLocked;
uint256 totalSupply;
uint256[] endsOfDistribution;
}
function blocksWithRewardsPassed(address _policyBook, uint256 _to)
external
view
returns (uint256);
function rewardPerToken(address _policyBook) external returns (uint256);
function earned(address _policyBook, address _account) external returns (uint256);
function updateTotalSupply(
address _policyBook,
uint256 newTotalSupply,
address liquidityProvider
) external;
function associateShieldMining(address _policyBook, address _shieldMiningToken) external;
function fillShieldMining(
address _policyBook,
uint256 _amount,
uint256 _duration
) external;
function getReward(address _policyBook) external;
/// @notice returns APY% with 10**5 precision
function getAPY(address _policyBook, uint256 _liquidityAdded) external view returns (uint256);
function recoverNonLockedRewardTokens(address _policyBook) external;
function getShieldTokenAddress(address _policyBook) external view returns (address);
function getUserRewardPaid(address _policyBook, address _account)
external
view
returns (uint256);
function getShieldMiningInfo(address _policyBook)
external
view
returns (ShieldMiningInfo memory _shieldMiningInfo);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPriceFeed {
function howManyBMIsInUSDT(uint256 usdtAmount) external view returns (uint256);
function howManyUSDTsInBMI(uint256 bmiAmount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
|
fetches all the pools data return uint256 VUreinsurnacePool return uint256 LUreinsurnacePool return uint256 LUleveragePool return uint256 user leverage pool address
|
function getPoolsData()
external
view
override
returns (
uint256,
uint256,
uint256,
address
)
{
uint256 _LUuserLeveragePool;
address _userLeverageAddress;
if (userLeveragePools.length() > 0) {
_LUuserLeveragePool = DecimalsConverter.convertFrom18(
LUuserLeveragePool[userLeveragePools.at(0)],
policyBook.stblDecimals()
);
_userLeverageAddress = userLeveragePools.at(0);
}
DecimalsConverter.convertFrom18(VUreinsurnacePool, policyBook.stblDecimals()),
DecimalsConverter.convertFrom18(LUreinsurnacePool, policyBook.stblDecimals()),
_LUuserLeveragePool,
_userLeverageAddress
);
}
| 6,093,392
|
./partial_match/1/0xBecC659Bfc6EDcA552fa1A67451cC6b38a0108E4/sources/FeeCollector.sol
|
uint minimumWeightChangeBlockPeriodParam, uint addTokenTimeLockInBlocksParam
|
interface ConfigurableRightsPool {
event LogCall(
bytes4 indexed sig,
address indexed caller,
bytes data
) anonymous;
event LogJoin(
address indexed caller,
address indexed tokenIn,
uint tokenAmountIn
);
event LogExit(
address indexed caller,
address indexed tokenOut,
uint tokenAmountOut
);
event CapChanged(
address indexed caller,
uint oldCap,
uint newCap
);
event NewTokenCommitted(
address indexed token,
address indexed pool,
address indexed caller
);
function createPool(
uint initialSupply
) external;
function createPool(
uint initialSupply,
uint minimumWeightChangeBlockPeriodParam,
uint addTokenTimeLockInBlocksParam
) external;
function updateWeightsGradually(
uint[] calldata newWeights,
uint startBlock,
uint endBlock
) external;
function joinswapExternAmountIn(
address tokenIn,
uint tokenAmountIn,
uint minPoolAmountOut
) external;
function whitelistLiquidityProvider(address provider) external;
function removeWhitelistedLiquidityProvider(address provider) external;
function canProvideLiquidity(address provider) external returns (bool);
function getController() external view returns (address);
function setController(address newOwner) external;
function transfer(address recipient, uint amount) external returns (bool);
function balanceOf(address account) external returns (uint);
function totalSupply() external returns (uint);
function bPool() external view returns (BPool);
function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external;
}
| 4,161,134
|
./full_match/122/0x26cDC2C58bDC2D3028A7a37F5D7e479eB7bf025C/sources/src/Facets/NXTPFacet.sol
|
This function performs a swap or multiple swaps and then starts a cross-chain transaction using the NXTP protocol. _bridgeData the core information needed for bridging _swapData array of data needed for swaps _nxtpData data needed to complete an NXTP cross-chain transaction
|
function swapAndStartBridgeTokensViaNXTP(
ILiFi.BridgeData memory _bridgeData,
LibSwap.SwapData[] calldata _swapData,
NXTPData calldata _nxtpData
)
external
payable
refundExcessNative(payable(msg.sender))
containsSourceSwaps(_bridgeData)
validateBridgeData(_bridgeData)
nonReentrant
{
if (hasDestinationCall(_nxtpData) != _bridgeData.hasDestinationCall) {
revert InformationMismatch();
}
validateInvariantData(_nxtpData.invariantData, _bridgeData);
_bridgeData.minAmount = _depositAndSwap(
_bridgeData.transactionId,
_bridgeData.minAmount,
_swapData,
payable(msg.sender)
);
_startBridge(_bridgeData, _nxtpData);
}
| 16,367,355
|
./full_match/9001/0x9b4A302A548c7e313c2b74C461db7b84d3074A84/sources/contracts/cross-chain-oracle/OracleSpoke.sol
|
Returns resolved price for the request. Reverts if price is not available. identifier Identifier of price request. time Timestamp of price request ancillaryData extra data of price request. return int256 Price, or reverts if no resolved price for any reason./
|
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override nonReentrantView() onlyRegisteredContract() returns (int256) {
bytes32 priceRequestId = _encodePriceRequest(identifier, time, _stampAncillaryData(ancillaryData));
Price storage lookup = prices[priceRequestId];
require(lookup.state == RequestState.Resolved, "Price has not been resolved");
return lookup.price;
}
| 11,534,451
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
contract NiFTyHextris is Context, ERC721 {
using Counters for Counters.Counter;
Counters.Counter private _tokenIdTracker;
string private _baseTokenURI;
RandomNumberConsumer randomNumberGeneratorContract;
struct Game {
uint256 startTime;
uint256 endTime;
uint256 points;
uint256 timeTaken;
}
event GameStarted(address indexed gamer, bytes32 indexed gameID, uint256 startTime);
event GameOver(address indexed gamer, bytes32 indexed gameID, uint256 endTime, uint256 points, uint256 timeTaken, uint256 indexed tokenId);
mapping(address => mapping(bytes32 => Game)) public Games;
constructor(string memory name, string memory symbol, string memory baseTokenURI, address _randomNumberGeneratorContract) public ERC721(name, symbol) {
_baseTokenURI = baseTokenURI;
randomNumberGeneratorContract = RandomNumberConsumer(_randomNumberGeneratorContract);
}
function startGame() public returns (bytes32 gameID) {
bytes32 _gameID = randomNumberGeneratorContract.getRandomNumber(block.timestamp);
Game memory newGame = Game({startTime: block.timestamp, endTime: 0, points: 0, timeTaken: 0});
Games[msg.sender][_gameID] = newGame;
emit GameStarted(msg.sender, _gameID, block.timestamp);
return _gameID;
}
function gameOver(bytes32 _gameID, uint256 _points) public virtual {
uint256 timeTaken = block.timestamp - Games[msg.sender][_gameID].startTime;
Games[msg.sender][_gameID].endTime = block.timestamp;
Games[msg.sender][_gameID].points = _points;
Games[msg.sender][_gameID].timeTaken = timeTaken;
uint256 tokenId = _tokenIdTracker.current();
_mint(msg.sender, tokenId);
_tokenIdTracker.increment();
emit GameOver(msg.sender, _gameID, block.timestamp, _points, timeTaken, tokenId);
}
}
// Polygon (Matic) Mumbai Testnet Deployment
// Taken from https://github.com/smartcontractkit/box/blob/master/contracts/RandomNumberConsumer.sol
contract RandomNumberConsumer is VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
uint256 public randomResult;
event RequestRandomness(bytes32 indexed requestId, bytes32 keyHash, uint256 seed);
event RequestRandomnessFulfilled(bytes32 indexed requestId, uint256 randomness);
/**
* Constructor inherits VRFConsumerBase
*
* Network: Polygon (Matic) Mumbai Testnet
* Chainlink VRF Coordinator address: 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255
* LINK token address: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
* Key Hash: 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4
* Fee: 0.001 * 10 ** 18; // 0.001 LINK
*/
constructor(address _vrfCoordinator, address _link, bytes32 _keyHash, uint256 _fee) public
VRFConsumerBase(
_vrfCoordinator, // VRF Coordinator
_link // LINK Token
)
{
keyHash = _keyHash;
fee = _fee;
}
/**
* Requests randomness based on the user input
*/
function getRandomNumber(uint256 userProvidedSeed) public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) > fee, "Not enough LINK to initialte function call");
uint256 seed = uint256(keccak256(abi.encode(userProvidedSeed, blockhash(block.number)))); // Hash user seed and blockhash
bytes32 _requestId = requestRandomness(keyHash, fee, seed);
emit RequestRandomness(_requestId, keyHash, seed);
return _requestId;
}
/**
* Requests the address of the Chainlink Token on this network
*/
function getChainlinkTokenAddress() public view returns (address) {
return address(LINK);
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
randomResult = randomness;
emit RequestRandomnessFulfilled(requestId, randomness);
}
}
|
Requests randomness based on the user input/
|
function getRandomNumber(uint256 userProvidedSeed) public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) > fee, "Not enough LINK to initialte function call");
bytes32 _requestId = requestRandomness(keyHash, fee, seed);
emit RequestRandomness(_requestId, keyHash, seed);
return _requestId;
}
| 12,875,992
|
./partial_match/4/0x29Df8785C95DB450f072F83A5654d27DBBE7a3E6/sources/Tantinople.sol
|
Withdraw LP tokens from Tantinople.
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
require(
pool.lock == false ||
(pool.lock && medal.totalSupply() >= halfPeriod)
);
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 userAmount = user.amount;
uint256 pending = userAmount.mul(pool.accMedalPerShare).div(1e12).sub(
user.rewardDebt
);
if (pending > 0) {
safeMedalTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
userAmount = userAmount.sub(_amount);
pool.totalAmount = pool.totalAmount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = userAmount.mul(pool.accMedalPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
| 8,655,697
|
./full_match/80001/0x7FE9D7703ee1a7D26fC95705b3a200a700751221/sources/_thirdweb-dev/contracts/extension/Staking20.sol
|
Set staking conditions.
|
function _setStakingCondition(
uint256 _timeUnit,
uint256 _numerator,
uint256 _denominator
) internal virtual {
require(_denominator != 0, "divide by 0");
require(_timeUnit != 0, "time-unit can't be 0");
uint256 conditionId = nextConditionId;
nextConditionId += 1;
stakingConditions[conditionId] = StakingCondition({
timeUnit: _timeUnit,
rewardRatioNumerator: _numerator,
rewardRatioDenominator: _denominator,
startTimestamp: block.timestamp,
endTimestamp: 0
});
if (conditionId > 0) {
stakingConditions[conditionId - 1].endTimestamp = block.timestamp;
}
}
| 868,760
|
/*
* v1.0.0
* proxy contract for WeCross
* main entrance of all contract call
*/
pragma solidity >=0.5.0 <0.6.0;
pragma experimental ABIEncoderV2;
contract WeCrossProxy {
string constant version = "v1.0.0";
// per step of xa transaction
struct XATransactionStep {
string accountIdentity;
uint256 timestamp;
string path;
address contractAddress;
string func;
bytes args;
}
// information of xa transaction
struct XATransaction {
string accountIdentity;
string[] paths; // all paths related to this transaction
address[] contractAddresses; // locked addressed in current chain
string status; // processing | committed | rolledback
uint256 startTimestamp;
uint256 commitTimestamp;
uint256 rollbackTimestamp;
uint256[] seqs; // sequence of each step
uint256 stepNum; // step number
}
struct ContractStatus {
bool locked; // isolation control, read-committed
string xaTransactionID;
}
mapping(address => ContractStatus) lockedContracts;
mapping(string => XATransaction) xaTransactions; // key: xaTransactionID
mapping(string => XATransactionStep) xaTransactionSteps; // key: xaTransactionID || xaTransactionSeq
/*
* record all xa transactionIDs
* head: point to the current xa transaction to be checked
* tail: point to the next position for added xa transaction
*/
uint256 head = 0;
uint256 tail = 0;
string[] xaTransactionIDs;
string constant XA_STATUS_PROCESSING = "processing";
string constant XA_STATUS_COMMITTED = "committed";
string constant XA_STATUS_ROLLEDBACK = "rolledback";
string constant REVERT_FLAG = "_revert";
string constant NULL_FLAG = "null";
string constant SUCCESS_FLAG = "success";
byte constant SEPARATOR = '.';
uint256 constant ADDRESS_LEN = 42;
uint256 constant MAX_SETP = 1024;
string[] pathCache;
struct Transaction {
bool existed;
bytes result;
}
mapping(string => Transaction) transactions; // key: uniqueID
CNSPrecompiled cns;
constructor() public {
cns = CNSPrecompiled(0x1004);
}
function getVersion() public pure
returns(string memory)
{
return version;
}
function addPath(string memory _path) public
{
pathCache.push(_path);
}
function getPaths() public view
returns (string[] memory)
{
return pathCache;
}
function deletePathList() public
{
pathCache.length = 0;
}
/*
* deploy contract by contract binary code
*/
function deployContract(bytes memory _bin) public returns(address addr) {
bool ok = false;
assembly {
addr := create(0,add(_bin,0x20), mload(_bin))
ok := gt(extcodesize(addr),0)
}
if(!ok) {
revert("deploy contract failed");
}
}
/**
* deploy contract and register contract to cns
*/
function deployContractWithRegisterCNS(string memory _path, string memory _version, bytes memory _bin, string memory _abi) public returns(address) {
string memory name = getNameByPath(_path);
address addr = getAddressByName(name, false);
if((addr != address(0x0)) && lockedContracts[addr].locked) {
revert(string(abi.encodePacked(name, " is locked by unfinished xa transaction: ", lockedContracts[addr].xaTransactionID)));
}
// deploy contract first
address deploy_addr = deployContract(_bin);
// register to cns
int ret = cns.insert(name, _version, addressToString(deploy_addr), _abi);
if(1 != ret) {
revert(string(abi.encodePacked(name, ":", _version, " unable register to cns, error: ", uint256ToString(uint256(ret > 0? ret : -ret)))));
}
pathCache.push(_path);
return deploy_addr;
}
/**
* register contract to cns
*/
function registerCNS(string memory _path, string memory _version, string memory _addr, string memory _abi) public {
string memory name = getNameByPath(_path);
address addr = getAddressByName(name, false);
if((addr != address(0x0)) && lockedContracts[addr].locked) {
revert(string(abi.encodePacked(name, " is locked by unfinished xa transaction: ", lockedContracts[addr].xaTransactionID)));
}
// check if version info exist ???
int ret = cns.insert(name, _version, _addr, _abi);
if(1 != ret) {
revert(string(abi.encodePacked(name, ":", _version, " unable register to cns, error: ", uint256ToString(uint256(ret > 0 ? ret : - ret)))));
}
pathCache.push(_path);
}
/**
* select cns by name
*/
function selectByName(string memory _name) public view returns(string memory) {
return cns.selectByName(_name);
}
/**
* select cns by name and version
*/
function selectByNameAndVersion(string memory _name, string memory _version) public view returns(string memory) {
return cns.selectByNameAndVersion(_name, _version);
}
// constant call with xaTransactionID
function constantCall(string memory _XATransactionID, string memory _path, string memory _func, bytes memory _args) public
returns(bytes memory)
{
address addr = getAddressByPath(_path);
if(!isExistedXATransaction(_XATransactionID)) {
revert("xa transaction not found");
}
if(!sameString(lockedContracts[addr].xaTransactionID, _XATransactionID)) {
revert(string(abi.encodePacked(_path, " is unregistered in xa transaction: ", _XATransactionID)));
}
return callContract(addr, _func, _args);
}
// constant call without xaTransactionID
function constantCall(string memory _name, bytes memory _argsWithMethodId) public
returns(bytes memory)
{
// find address from abi cache first
address addr = getAddressByName(_name, true);
if(lockedContracts[addr].locked) {
revert(string(abi.encodePacked("resource is locked by unfinished xa transaction: ", lockedContracts[addr].xaTransactionID)));
}
return callContract(addr, _argsWithMethodId);
}
// non-constant call with xaTransactionID
function sendTransaction(string memory _uid, string memory _XATransactionID, uint256 _XATransactionSeq, string memory _path, string memory _func, bytes memory _args) public
returns(bytes memory)
{
if(transactions[_uid].existed) {
return transactions[_uid].result;
}
address addr = getAddressByPath(_path);
if(!isExistedXATransaction(_XATransactionID)) {
revert("xa transaction not found");
}
if(sameString(xaTransactions[_XATransactionID].status, XA_STATUS_COMMITTED)) {
revert("xa transaction has been committed");
}
if(sameString(xaTransactions[_XATransactionID].status, XA_STATUS_ROLLEDBACK)) {
revert("xa transaction has been rolledback");
}
if(!sameString(lockedContracts[addr].xaTransactionID, _XATransactionID)) {
revert(string(abi.encodePacked(_path, " is unregistered in xa transaction ", _XATransactionID)));
}
if(!isValidXATransactionSep(_XATransactionID, _XATransactionSeq)) {
revert("seq should be greater than before");
}
// recode step
xaTransactionSteps[getXATransactionStepKey(_XATransactionID, _XATransactionSeq)] = XATransactionStep(
addressToString(tx.origin),
block.timestamp / 1000,
_path,
addr,
_func,
_args
);
// recode seq
uint256 num = xaTransactions[_XATransactionID].stepNum;
xaTransactions[_XATransactionID].seqs[num] = _XATransactionSeq;
xaTransactions[_XATransactionID].stepNum = num + 1;
bytes memory result = callContract(addr, _func, _args);
// recode transaction
transactions[_uid] = Transaction(true, result);
return result;
}
// non-constant call without xaTransactionID
function sendTransaction(string memory _uid, string memory _name, bytes memory _argsWithMethodId) public returns(bytes memory) {
if(transactions[_uid].existed) {
return transactions[_uid].result;
}
// find address from abi cache first
address addr = getAddressByName(_name, true);
if(lockedContracts[addr].locked) {
revert(string(abi.encodePacked(_name, " is locked by unfinished xa transaction: ", lockedContracts[addr].xaTransactionID)));
}
bytes memory result = callContract(addr, _argsWithMethodId);
// recode transaction
transactions[_uid] = Transaction(true, result);
return result;
}
/*
* @param xaTransactionID
* @param selfPaths are related to current chain
* result: success
*/
function startXATransaction(string memory _xaTransactionID, string[] memory _selfPaths, string[] memory _otherPaths) public
returns(string memory)
{
if(isExistedXATransaction(_xaTransactionID)) {
revert(string(abi.encodePacked("xa transaction ", _xaTransactionID, " already exists")));
}
uint256 selfLen = _selfPaths.length;
uint256 otherLen = _otherPaths.length;
address[] memory contracts = new address[](selfLen);
string[] memory allPaths = new string[](selfLen + otherLen);
// recode ACL
for(uint256 i = 0; i < selfLen; i++) {
address addr = getAddressByPath(_selfPaths[i]);
contracts[i] = addr;
if(lockedContracts[addr].locked) {
revert(string(abi.encodePacked(_selfPaths[i], " is locked by unfinished xa transaction: ", lockedContracts[addr].xaTransactionID)));
}
lockedContracts[addr].locked = true;
lockedContracts[addr].xaTransactionID = _xaTransactionID;
allPaths[i] = _selfPaths[i];
}
for(uint256 i = 0; i < otherLen; i++)
{
allPaths[selfLen+i] = _otherPaths[i];
}
uint256[] memory seqs = new uint256[](MAX_SETP);
// recode xa transaction
xaTransactions[_xaTransactionID] = XATransaction(
addressToString(tx.origin),
allPaths,
contracts,
XA_STATUS_PROCESSING,
block.timestamp / 1000,
0,
0,
seqs,
0
);
addXATransaction(_xaTransactionID);
return SUCCESS_FLAG;
}
/*
* @param xaTransactionID
* result: success
*/
function commitXATransaction(string memory _xaTransactionID) public
returns(string memory)
{
if(!isExistedXATransaction(_xaTransactionID)) {
revert("xa transaction not found");
}
// has committed
if(sameString(xaTransactions[_xaTransactionID].status, XA_STATUS_COMMITTED)) {
revert("xa transaction has been committed");
}
// has rolledback
if(sameString(xaTransactions[_xaTransactionID].status, XA_STATUS_ROLLEDBACK)) {
revert("xa transaction has been rolledback");
}
xaTransactions[_xaTransactionID].commitTimestamp = block.timestamp / 1000;
xaTransactions[_xaTransactionID].status = XA_STATUS_COMMITTED;
deleteLockedContracts(_xaTransactionID);
return SUCCESS_FLAG;
}
/*
* @param xaTransactionID
* result: success | message
*/
function rollbackXATransaction(string memory _xaTransactionID) public
returns(string memory)
{
string memory result = SUCCESS_FLAG;
if(!isExistedXATransaction(_xaTransactionID)) {
revert("xa transaction not found");
}
// has committed
if(sameString(xaTransactions[_xaTransactionID].status, XA_STATUS_COMMITTED)) {
revert("xa transaction has been committed");
}
// has rolledback
if(sameString(xaTransactions[_xaTransactionID].status, XA_STATUS_ROLLEDBACK)) {
revert("xa transaction has been rolledback");
}
string memory message = 'warning:';
uint256 stepNum = xaTransactions[_xaTransactionID].stepNum;
for(uint256 i = stepNum; i > 0; i--) {
uint256 seq = xaTransactions[_xaTransactionID].seqs[i-1];
string memory key = getXATransactionStepKey(_xaTransactionID, seq);
string memory func = xaTransactionSteps[key].func;
address contractAddress = xaTransactionSteps[key].contractAddress;
bytes memory args = xaTransactionSteps[key].args;
// call revert function
bytes memory sig = abi.encodeWithSignature(getRevertFunc(func, REVERT_FLAG));
bool success;
(success, ) = address(contractAddress).call(abi.encodePacked(sig, args));
if(!success) {
message = string(abi.encodePacked(message, ' revert "', func, '" failed.'));
result = message;
}
}
xaTransactions[_xaTransactionID].rollbackTimestamp = block.timestamp / 1000;
xaTransactions[_xaTransactionID].status = XA_STATUS_ROLLEDBACK;
deleteLockedContracts(_xaTransactionID);
return result;
}
function getXATransactionNumber() public view
returns (string memory)
{
if(xaTransactionIDs.length == 0) {
return "0";
} else {
return uint256ToString(xaTransactionIDs.length);
}
}
/*
* traverse in reverse order
* outputs:
{
"total": 100,
"xaTransactions":
[
{
"xaTransactionID": "001",
"accountIdentity": "0x11",
"status": "processing",
"timestamp": 123,
"paths": ["a.b.1","a.b.2"]
},
{
"xaTransactionID": "002",
"accountIdentity": "0x11",
"status": "committed",
"timestamp": 123,
"paths": ["a.b.1","a.b.2"]
}
]
}
*/
function listXATransactions(string memory _index, uint256 _size) public view
returns (string memory)
{
uint256 len = xaTransactionIDs.length;
uint256 index = sameString("-1", _index) ? (len - 1) : stringToUint256(_index);
if(len == 0 || len <= index) {
return '{"total":0,"xaTransactions":[]}';
}
string memory jsonStr = '[';
for(uint256 i = 0; i < (_size - 1) && (index - i) > 0; i++) {
string memory xaTransactionID = xaTransactionIDs[index-i];
jsonStr = string(abi.encodePacked(jsonStr, '{"xaTransactionID":"', xaTransactionID, '",',
'"accountIdentity":"', xaTransactions[xaTransactionID].accountIdentity, '",',
'"status":"', xaTransactions[xaTransactionID].status, '",',
'"paths":', pathsToJson(xaTransactionID), ',',
'"timestamp":', uint256ToString(xaTransactions[xaTransactionID].startTimestamp), '},')
);
}
uint256 lastIndex = (index + 1) >= _size ? (index + 1 - _size) : 0;
string memory xaTransactionID = xaTransactionIDs[lastIndex];
jsonStr = string(abi.encodePacked(jsonStr, '{"xaTransactionID":"', xaTransactionID, '",',
'"accountIdentity":"', xaTransactions[xaTransactionID].accountIdentity, '",',
'"status":"', xaTransactions[xaTransactionID].status, '",',
'"paths":', pathsToJson(xaTransactionID), ',',
'"timestamp":', uint256ToString(xaTransactions[xaTransactionID].startTimestamp), '}]')
);
return string(abi.encodePacked('{"total":', uint256ToString(len),',"xaTransactions":', jsonStr, '}'));
}
/*
* @param xaTransactionID
* result with json form
* example:
{
"xaTransactionID": "1",
"accountIdentity": "0x88",
"status": "processing",
"paths":["a.b.c1","a.b.c2","a.b1.c3"],
"startTimestamp": 123,
"commitTimestamp": 456,
"rollbackTimestamp": 0,
"xaTransactionSteps": [{
"accountIdentity":"0x12",
"xaTransactionSeq": 233,
"path": "a.b.c1",
"timestamp": 233,
"method": "set",
"args": "0010101"
},
{
"accountIdentity":"0x12",
"xaTransactionSeq": 244,
"path": "a.b.c2",
"timestamp": 244,
"method": "set",
"args": "0010101"
}
]
}
*/
function getXATransaction(string memory _xaTransactionID) public view
returns(string memory)
{
if(!isExistedXATransaction(_xaTransactionID)) {
revert("xa transaction not found");
}
return string(abi.encodePacked('{"xaTransactionID":"', _xaTransactionID, '",',
'"accountIdentity":"', xaTransactions[_xaTransactionID].accountIdentity, '",',
'"status":"', xaTransactions[_xaTransactionID].status, '",',
'"paths":', pathsToJson(_xaTransactionID), ',',
'"startTimestamp":', uint256ToString(xaTransactions[_xaTransactionID].startTimestamp), ',',
'"commitTimestamp":', uint256ToString(xaTransactions[_xaTransactionID].commitTimestamp), ',',
'"rollbackTimestamp":', uint256ToString(xaTransactions[_xaTransactionID].rollbackTimestamp), ',',
'"xaTransactionSteps":', xaTransactionStepArrayToJson(_xaTransactionID, xaTransactions[_xaTransactionID].seqs, xaTransactions[_xaTransactionID].stepNum), "}")
);
}
// called by router to check xa transaction status
function getLatestXATransaction() public view
returns(string memory)
{
string memory xaTransactionID;
if(head == tail) {
return '{}';
} else {
xaTransactionID = xaTransactionIDs[uint256(head)];
}
return getXATransaction(xaTransactionID);
}
// called by router to rollbach transaction
function rollbackAndDeleteXATransactionTask(string memory _xaTransactionID) public
returns (string memory)
{
rollbackXATransaction(_xaTransactionID);
return deleteXATransactionTask(_xaTransactionID);
}
function getLatestXATransactionID() public view
returns (string memory)
{
if(head == tail) {
return NULL_FLAG;
} else {
return xaTransactionIDs[uint256(head)];
}
}
function getXATransactionState(string memory _path) public view
returns (string memory)
{
address addr = getAddressByPath(_path);
if(!lockedContracts[addr].locked) {
return NULL_FLAG;
} else {
string memory xaTransactionID = lockedContracts[addr].xaTransactionID;
uint256 index = xaTransactions[xaTransactionID].stepNum;
uint256 seq = index == 0 ? 0 : xaTransactions[xaTransactionID].seqs[index-1];
return string(abi.encodePacked(xaTransactionID, " ", uint256ToString(seq)));
}
}
function addXATransaction(string memory _xaTransactionID) internal
{
tail++;
xaTransactionIDs.push(_xaTransactionID);
}
function deleteXATransactionTask(string memory _xaTransactionID) internal
returns (string memory)
{
if(head == tail) {
revert("delete nonexistent xa transaction");
}
if(!sameString(xaTransactionIDs[head], _xaTransactionID)) {
revert("delete unmatched xa transaction");
}
head++;
return SUCCESS_FLAG;
}
// internal call
function callContract(address _contractAddress, string memory _sig, bytes memory _args) internal
returns(bytes memory result)
{
bytes memory sig = abi.encodeWithSignature(_sig);
bool success;
(success, result) = address(_contractAddress).call(abi.encodePacked(sig, _args));
if(!success) {
revert(string(result));
}
}
// internal call
function callContract(address _contractAddress, bytes memory _argsWithMethodId) internal
returns(bytes memory result)
{
bool success;
(success, result) = address(_contractAddress).call(_argsWithMethodId);
if(!success) {
//(string memory error) = abi.decode(result, (string));
revert(string(result));
}
}
// retrive address from CNS
function getAddressByName(string memory _name, bool revertNotExist) internal view
returns (address)
{
string memory strJson = cns.selectByName(_name);
bytes memory str = bytes(strJson);
uint256 len = str.length;
uint256 index = newKMP(str, bytes("\"sserdda\""));
if(index == 0) {
if(revertNotExist) {
revert("the name's address not exist.");
}
return address(0x0);
}
bytes memory addr = new bytes(ADDRESS_LEN);
uint256 start = 0;
for(uint256 i = index; i < len; i++) {
if(str[i] == byte('0') && str[i+1] == byte('x')) {
start = i;
break;
}
}
for(uint256 i = 0; i < ADDRESS_LEN; i++) {
addr[i] = str[start + i];
}
return bytesToAddress(addr);
}
// retrive address from CNS
function getAddressByPath(string memory _path) internal view
returns (address)
{
string memory name = getNameByPath(_path);
return getAddressByName(name, true);
}
// input must be a valid path like "zone.chain.resource"
function getNameByPath(string memory _path) internal pure
returns (string memory)
{
bytes memory path = bytes(_path);
uint256 len = path.length;
uint256 nameLen = 0;
uint256 index = 0;
for(uint256 i = len - 1; i > 0; i--) {
if(path[i] == SEPARATOR) {
index = i + 1;
break;
} else {
nameLen++;
}
}
bytes memory name = new bytes(nameLen);
for(uint256 i = 0; i < nameLen; i++) {
name[i] = path[index++];
}
return string(name);
}
/*
["a.b.c1", "a.b.c2"]
*/
function pathsToJson(string memory _transactionID) internal view
returns(string memory)
{
uint256 len = xaTransactions[_transactionID].paths.length;
string memory paths = string(abi.encodePacked('["', xaTransactions[_transactionID].paths[0], '"'));
for(uint256 i = 1; i < len; i++) {
paths = string(abi.encodePacked(paths, ',"', xaTransactions[_transactionID].paths[i], '"'));
}
return string(abi.encodePacked(paths, ']'));
}
/*
[
{
"accountIdentity":"0x12",
"xaTransactionSeq": 233,
"path": "a.b.c1",
"timestamp": 233,
"method": "set",
"args": "0010101"
},
{
"accountIdentity":"0x12",
"xaTransactionSeq": 233,
"path": "a.b.c1",
"timestamp": 233,
"method": "set",
"args": "0010101"
}
]
*/
function xaTransactionStepArrayToJson(string memory _transactionID, uint256[] memory _seqs, uint256 _len) internal view
returns(string memory result)
{
if(_len == 0) {
return '[]';
}
result = string(abi.encodePacked('[', xatransactionStepToJson(xaTransactionSteps[getXATransactionStepKey(_transactionID, _seqs[0])], _seqs[0])));
for(uint256 i = 1; i < _len; i++) {
result = string(abi.encodePacked(result, ',', xatransactionStepToJson(xaTransactionSteps[getXATransactionStepKey(_transactionID, _seqs[i])], _seqs[i])));
}
return string(abi.encodePacked(result, ']'));
}
/*
{
"xaTransactionSeq": 233,
"accountIdentity":"0x12",
"path": "a.b.c1",
"timestamp": 233,
"method": "set",
"args": "0010101"
}
*/
function xatransactionStepToJson(XATransactionStep memory _xaTransactionStep, uint256 _XATransactionSeq) internal pure
returns(string memory)
{
return string(abi.encodePacked('{"xaTransactionSeq":', uint256ToString(_XATransactionSeq), ',',
'"accountIdentity":"', _xaTransactionStep.accountIdentity, '",',
'"path":"', _xaTransactionStep.path, '",',
'"timestamp":', uint256ToString(_xaTransactionStep.timestamp), ',',
'"method":"', getMethodFromFunc(_xaTransactionStep.func), '",',
'"args":"', bytesToHexString(_xaTransactionStep.args), '"}')
);
}
function isExistedXATransaction(string memory _xaTransactionID) internal view
returns (bool)
{
return xaTransactions[_xaTransactionID].startTimestamp != 0;
}
function isValidXATransactionSep(string memory _xaTransactionID, uint256 _XATransactionSeq) internal view
returns(bool)
{
uint256 index = xaTransactions[_xaTransactionID].stepNum;
return (index == 0) || (_XATransactionSeq > xaTransactions[_xaTransactionID].seqs[index-1]);
}
function deleteLockedContracts(string memory _xaTransactionID) internal
{
uint256 len = xaTransactions[_xaTransactionID].contractAddresses.length;
for(uint256 i = 0; i < len; i++) {
address contractAddress = xaTransactions[_xaTransactionID].contractAddresses[i];
delete lockedContracts[contractAddress];
}
}
/* a famous algorithm for finding substring
match starts with tail, and the target must be "\"sserdda\""
*/
function newKMP(bytes memory _str, bytes memory _target) internal pure
returns (uint256)
{
int256 strLen = int256(_str.length);
int256 tarLen = int256(_target.length);
// next array for target "\"sserdda\""
int8[9] memory nextArray = [-1,0,0,0,0,0,0,0,0];
int256 i = strLen;
int256 j = 0;
while (i > 0 && j < tarLen) {
if (j == -1 || _str[uint256(i-1)] == _target[uint256(j)]) {
i--;
j++;
} else {
j = int256(nextArray[uint256(j)]);
}
}
if ( j == tarLen) {
return uint256(i + tarLen);
}
return 0;
}
// func(string,uint256) => func_flag(string,uint256)
function getRevertFunc(string memory _func, string memory _revertFlag) internal pure
returns(string memory)
{
bytes memory funcBytes = bytes(_func);
bytes memory flagBytes = bytes(_revertFlag);
uint256 funcLen = funcBytes.length;
uint256 flagLen = flagBytes.length;
bytes memory newFunc = new bytes(funcLen + flagLen);
byte c = byte('(');
uint256 index = 0;
uint256 point = 0;
for(uint256 i = 0; i < funcLen; i++) {
if(funcBytes[i] != c) {
newFunc[index++] = funcBytes[i];
} else {
point = i;
break;
}
}
for(uint256 i = 0; i < flagLen; i++) {
newFunc[index++] = flagBytes[i];
}
for(uint256 i = point; i < funcLen; i++) {
newFunc[index++] = funcBytes[i];
}
return string(newFunc);
}
// func(string,uint256) => func
function getMethodFromFunc(string memory _func) internal pure
returns(string memory)
{
bytes memory funcBytes = bytes(_func);
uint256 funcLen = funcBytes.length;
bytes memory temp = new bytes(funcLen);
byte c = byte('(');
uint256 index = 0;
for(uint256 i = 0; i < funcLen; i++) {
if(funcBytes[i] != c) {
temp[index++] = funcBytes[i];
} else {
break;
}
}
bytes memory result = new bytes(index);
for(uint256 i = 0; i < index; i++) {
result[i] = temp[i];
}
return string(result);
}
function getXATransactionStepKey(string memory _transactionID, uint256 _transactionSeq) internal pure
returns(string memory)
{
return string(abi.encodePacked(_transactionID, uint256ToString(_transactionSeq)));
}
function sameString(string memory _str1, string memory _str2) internal pure
returns (bool)
{
return keccak256(bytes(_str1)) == keccak256(bytes(_str2));
}
function hexStringToBytes(string memory _hexStr) internal pure
returns (bytes memory)
{
bytes memory bts = bytes(_hexStr);
require(bts.length%2 == 0);
bytes memory result = new bytes(bts.length/2);
uint len = bts.length/2;
for (uint i = 0; i < len; ++i) {
result[i] = byte(fromHexChar(uint8(bts[2*i])) * 16 +
fromHexChar(uint8(bts[2*i+1])));
}
return result;
}
function fromHexChar(uint8 _char) internal pure
returns (uint8)
{
if (byte(_char) >= byte('0') && byte(_char) <= byte('9')) {
return _char - uint8(byte('0'));
}
if (byte(_char) >= byte('a') && byte(_char) <= byte('f')) {
return 10 + _char - uint8(byte('a'));
}
if (byte(_char) >= byte('A') && byte(_char) <= byte('F')) {
return 10 + _char - uint8(byte('A'));
}
}
function stringToUint256(string memory _str) public pure
returns (uint256)
{
bytes memory bts = bytes(_str);
uint256 result = 0;
uint256 len = bts.length;
for (uint256 i = 0; i < len; i++) {
if (uint8(bts[i]) >= 48 && uint8(bts[i]) <= 57) {
result = result * 10 + (uint8(bts[i]) - 48);
}
}
return result;
}
function uint256ToString(uint256 _value) internal pure
returns (string memory)
{
bytes32 result;
if (_value == 0) {
return "0";
} else {
while (_value > 0) {
result = bytes32(uint(result) / (2 ** 8));
result |= bytes32(((_value % 10) + 48) * 2 ** (8 * 31));
_value /= 10;
}
}
return bytes32ToString(result);
}
function bytesToHexString(bytes memory _bts) internal pure
returns (string memory result)
{
uint256 len = _bts.length;
bytes memory s = new bytes(len * 2);
for (uint256 i = 0; i < len; i++) {
byte befor = byte(_bts[i]);
byte high = byte(uint8(befor) / 16);
byte low = byte(uint8(befor) - 16 * uint8(high));
s[i*2] = convert(high);
s[i*2+1] = convert(low);
}
result = string(s);
}
function bytes32ToString(bytes32 _bts32) internal pure
returns (string memory)
{
bytes memory result = new bytes(_bts32.length);
uint len = _bts32.length;
for(uint i = 0; i < len; i++) {
result[i] = _bts32[i];
}
return string(result);
}
function bytesToAddress(bytes memory _address) internal pure
returns (address)
{
if(_address.length != 42) {
revert(string(abi.encodePacked("cannot covert ", _address, "to bcos address")));
}
uint160 result = 0;
uint160 b1;
uint160 b2;
for (uint i = 2; i < 2 + 2 * 20; i += 2) {
result *= 256;
b1 = uint160(uint8(_address[i]));
b2 = uint160(uint8(_address[i + 1]));
if ((b1 >= 97) && (b1 <= 102)) {
b1 -= 87;
} else if ((b1 >= 65) && (b1 <= 70)) {
b1 -= 55;
} else if ((b1 >= 48) && (b1 <= 57)) {
b1 -= 48;
}
if ((b2 >= 97) && (b2 <= 102)) {
b2 -= 87;
} else if ((b2 >= 65) && (b2 <= 70)) {
b2 -= 55;
} else if ((b2 >= 48) && (b2 <= 57)) {
b2 -= 48;
}
result += (b1 * 16 + b2);
}
return address(result);
}
function addressToString(address _addr) internal pure
returns (string memory)
{
bytes memory result = new bytes(40);
for (uint i = 0; i < 20; i++) {
byte temp = byte(uint8(uint(_addr) / (2 ** (8 * (19 - i)))));
byte b1 = byte(uint8(temp) / 16);
byte b2 = byte(uint8(temp) - 16 * uint8(b1));
result[2 * i] = convert(b1);
result[2 * i + 1] = convert(b2);
}
return string(abi.encodePacked("0x", string(result)));
}
function convert(byte _b) internal pure
returns (byte)
{
if (uint8(_b) < 10) {
return byte(uint8(_b) + 0x30);
} else {
return byte(uint8(_b) + 0x57);
}
}
}
contract CNSPrecompiled {
function insert(string memory name, string memory version, string memory addr, string memory abiStr) public returns(int256);
function selectByName(string memory name) public view returns (string memory);
function selectByNameAndVersion(string memory name, string memory version) public view returns (string memory);
}
|
retrive address from CNS
|
function getAddressByPath(string memory _path) internal view
returns (address)
{
string memory name = getNameByPath(_path);
return getAddressByName(name, true);
}
| 1,813,359
|
./full_match/80001/0xcBba3dc6457C94285258F591Fd67A9588c812df7/sources/project_/contracts/STokenV1.sol
|
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 and has to be whitelisted. Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
|
function _mint(address _account, uint256 _amount)
internal
onlyWhitelisted(_account)
{
require(_account != address(0), "STokenV1: mint to the zero address");
_totalSupply += _amount;
unchecked {
_balances[_account] += _amount;
}
emit Transfer(address(0), _account, _amount);
}
| 851,994
|
./full_match/44787/0x9c6b5c13Fd62be150e5a3AE74FC5bB1b87348bBD/sources/contracts/StarFarm.sol
|
Withdraw Star NFT from STAKING.
|
function leaveStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 pending = (user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100))).mul(pool.accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.amount);
}
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));
pool.extraAmount = pool.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));
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _amount, isNodeUser[_msgSender()]);
break;
}
}
}
}
| 13,252,623
|
//Address: 0xc22462d4bc50952b061c9e6c585fdd9a04d0d75a
//Contract name: Contribution
//Balance: 0 Ether
//Verification Date: 9/9/2017
//Transacion Count: 6582
// CODE STARTS HERE
pragma solidity ^0.4.15;
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount)
returns(bool);
}
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) onlyController {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data);
}
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.1'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer returns false
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
Transfer(_from, _to, _amount);
return true;
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) returns (bool success) {
require(transfersEnabled);
// 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((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
contract CND is MiniMeToken {
/**
* @dev Constructor
*/
uint256 public constant IS_CND_CONTRACT_MAGIC_NUMBER = 0x1338;
function CND(address _tokenFactory)
MiniMeToken(
_tokenFactory,
0x0, // no parent token
0, // no snapshot block number from parent
"Cindicator Token", // Token name
18, // Decimals
"CND", // Symbol
true // Enable transfers
)
{}
function() payable {
require(false);
}
}
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Contribution is Controlled, TokenController {
using SafeMath for uint256;
struct WhitelistedInvestor {
uint256 tier;
bool status;
uint256 contributedAmount;
}
mapping(address => WhitelistedInvestor) investors;
Tier[4] public tiers;
uint256 public tierCount;
MiniMeToken public cnd;
bool public transferable = false;
uint256 public October12_2017 = 1507830400;
address public contributionWallet;
address public foundersWallet;
address public advisorsWallet;
address public bountyWallet;
bool public finalAllocation;
uint256 public totalTokensSold;
bool public paused = false;
modifier notAllocated() {
require(finalAllocation == false);
_;
}
modifier endedSale() {
require(tierCount == 4); //when last one finished it should be equal to 4
_;
}
modifier tokenInitialized() {
assert(address(cnd) != 0x0);
_;
}
modifier initialized() {
Tier tier = tiers[tierCount];
assert(tier.initializedTime() != 0);
_;
}
/// @notice Provides information if contribution is open
/// @return False if the contribuion is closed
function contributionOpen() public constant returns(bool) {
Tier tier = tiers[tierCount];
return (getBlockTimestamp() >= tier.startTime() &&
getBlockTimestamp() <= tier.endTime() &&
tier.finalizedTime() == 0);
}
modifier notPaused() {
require(!paused);
_;
}
function Contribution(address _contributionWallet, address _foundersWallet, address _advisorsWallet, address _bountyWallet) {
require(_contributionWallet != 0x0);
require(_foundersWallet != 0x0);
require(_advisorsWallet != 0x0);
require(_bountyWallet != 0x0);
contributionWallet = _contributionWallet;
foundersWallet = _foundersWallet;
advisorsWallet =_advisorsWallet;
bountyWallet = _bountyWallet;
tierCount = 0;
}
/// @notice Initializes CND token to contribution
/// @param _cnd The address of the token contract that you want to set
function initializeToken(address _cnd) public onlyController {
assert(CND(_cnd).controller() == address(this));
assert(CND(_cnd).IS_CND_CONTRACT_MAGIC_NUMBER() == 0x1338);
require(_cnd != 0x0);
cnd = CND(_cnd);
}
/// @notice Initializes Tier contribution
/// @param _tierNumber number of tier to initialize
/// @param _tierAddress address of deployed tier
function initializeTier(
uint256 _tierNumber,
address _tierAddress
) public onlyController tokenInitialized
{
Tier tier = Tier(_tierAddress);
assert(tier.controller() == address(this));
//cannot be more than 4 tiers
require(_tierNumber >= 0 && _tierNumber <= 3);
assert(tier.IS_TIER_CONTRACT_MAGIC_NUMBER() == 0x1337);
// check if tier is not defined
assert(tiers[_tierNumber] == address(0));
tiers[_tierNumber] = tier;
InitializedTier(_tierNumber, _tierAddress);
}
/// @notice If anybody sends Ether directly to this contract, consider the sender will
/// be rejected.
function () public {
require(false);
}
/// @notice Amount of tokens an investor can purchase
/// @param _investor investor address
/// @return number of tokens
function investorAmountTokensToBuy(address _investor) public constant returns(uint256) {
WhitelistedInvestor memory investor = investors[_investor];
Tier tier = tiers[tierCount];
uint256 leftToBuy = tier.maxInvestorCap().sub(investor.contributedAmount).mul(tier.exchangeRate());
return leftToBuy;
}
/// @notice Notifies if an investor is whitelisted for contribution
/// @param _investor investor address
/// @param _tier tier Number
/// @return number of tokens
function isWhitelisted(address _investor, uint256 _tier) public constant returns(bool) {
WhitelistedInvestor memory investor = investors[_investor];
return (investor.tier <= _tier && investor.status);
}
/// @notice interface for founders to whitelist investors
/// @param _addresses array of investors
/// @param _tier tier Number
/// @param _status enable or disable
function whitelistAddresses(address[] _addresses, uint256 _tier, bool _status) public onlyController {
for (uint256 i = 0; i < _addresses.length; i++) {
address investorAddress = _addresses[i];
require(investors[investorAddress].contributedAmount == 0);
investors[investorAddress] = WhitelistedInvestor(_tier, _status, 0);
}
}
/// @notice Public function to buy tokens
function buy() public payable {
proxyPayment(msg.sender);
}
/// use buy function instead of proxyPayment
/// the param address is useless, it always reassigns to msg.sender
function proxyPayment(address) public payable
notPaused
initialized
returns (bool)
{
assert(isCurrentTierCapReached() == false);
assert(contributionOpen());
require(isWhitelisted(msg.sender, tierCount));
doBuy();
return true;
}
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @return False if the controller does not authorize the transfer
function onTransfer(address /* _from */, address /* _to */, uint256 /* _amount */) returns(bool) {
return (transferable || getBlockTimestamp() >= October12_2017 );
}
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @return False if the controller does not authorize the approval
function onApprove(address /* _owner */, address /* _spender */, uint /* _amount */) returns(bool) {
return (transferable || getBlockTimestamp() >= October12_2017);
}
/// @notice Allows founders to set transfers before October12_2017
/// @param _transferable set True if founders want to let people make transfers
function allowTransfers(bool _transferable) onlyController {
transferable = _transferable;
}
/// @notice calculates how many tokens left for sale
/// @return Number of tokens left for tier
function leftForSale() public constant returns(uint256) {
Tier tier = tiers[tierCount];
uint256 weiLeft = tier.cap().sub(tier.totalInvestedWei());
uint256 tokensLeft = weiLeft.mul(tier.exchangeRate());
return tokensLeft;
}
/// @notice actual method that funds investor and contribution wallet
function doBuy() internal {
Tier tier = tiers[tierCount];
assert(msg.value <= tier.maxInvestorCap());
address caller = msg.sender;
WhitelistedInvestor storage investor = investors[caller];
uint256 investorTokenBP = investorAmountTokensToBuy(caller);
require(investorTokenBP > 0);
if(investor.contributedAmount == 0) {
assert(msg.value >= tier.minInvestorCap());
}
uint256 toFund = msg.value;
uint256 tokensGenerated = toFund.mul(tier.exchangeRate());
// check that at least 1 token will be generated
require(tokensGenerated >= 1);
uint256 tokensleftForSale = leftForSale();
if(tokensleftForSale > investorTokenBP ) {
if(tokensGenerated > investorTokenBP) {
tokensGenerated = investorTokenBP;
toFund = investorTokenBP.div(tier.exchangeRate());
}
}
if(investorTokenBP > tokensleftForSale) {
if(tokensGenerated > tokensleftForSale) {
tokensGenerated = tokensleftForSale;
toFund = tokensleftForSale.div(tier.exchangeRate());
}
}
investor.contributedAmount = investor.contributedAmount.add(toFund);
tier.increaseInvestedWei(toFund);
if (tokensGenerated == tokensleftForSale) {
finalize();
}
assert(cnd.generateTokens(caller, tokensGenerated));
totalTokensSold = totalTokensSold.add(tokensGenerated);
contributionWallet.transfer(toFund);
NewSale(caller, toFund, tokensGenerated);
uint256 toReturn = msg.value.sub(toFund);
if (toReturn > 0) {
caller.transfer(toReturn);
Refund(toReturn);
}
}
/// @notice This method will can be called by the anybody to make final allocation
/// @return result if everything went succesfully
function allocate() public notAllocated endedSale returns(bool) {
finalAllocation = true;
uint256 totalSupplyCDN = totalTokensSold.mul(100).div(75); // calculate 100%
uint256 foundersAllocation = totalSupplyCDN.div(5); // 20% goes to founders
assert(cnd.generateTokens(foundersWallet, foundersAllocation));
uint256 advisorsAllocation = totalSupplyCDN.mul(38).div(1000); // 3.8% goes to advisors
assert(cnd.generateTokens(advisorsWallet, advisorsAllocation));
uint256 bountyAllocation = totalSupplyCDN.mul(12).div(1000); // 1.2% goes to bounty program
assert(cnd.generateTokens(bountyWallet, bountyAllocation));
return true;
}
/// @notice This method will can be called by the controller after the contribution period
/// end or by anybody after the `endTime`. This method finalizes the contribution period
function finalize() public initialized {
Tier tier = tiers[tierCount];
assert(tier.finalizedTime() == 0);
assert(getBlockTimestamp() >= tier.startTime());
assert(msg.sender == controller || getBlockTimestamp() > tier.endTime() || isCurrentTierCapReached());
tier.finalize();
tierCount++;
FinalizedTier(tierCount, tier.finalizedTime());
}
/// @notice check if tier cap has reached
/// @return False if it's still open
function isCurrentTierCapReached() public constant returns(bool) {
Tier tier = tiers[tierCount];
return tier.isCapReached();
}
//////////
// Testing specific methods
//////////
function getBlockTimestamp() internal constant returns (uint256) {
return block.timestamp;
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (cnd.controller() == address(this)) {
cnd.claimTokens(_token);
}
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
CND token = CND(_token);
uint256 balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
/// @notice Pauses the contribution if there is any issue
function pauseContribution(bool _paused) onlyController {
paused = _paused;
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event NewSale(address indexed _th, uint256 _amount, uint256 _tokens);
event InitializedTier(uint256 _tierNumber, address _tierAddress);
event FinalizedTier(uint256 _tierCount, uint256 _now);
event Refund(uint256 _amount);
}
contract Tier is Controlled {
using SafeMath for uint256;
uint256 public cap;
uint256 public exchangeRate;
uint256 public minInvestorCap;
uint256 public maxInvestorCap;
uint256 public startTime;
uint256 public endTime;
uint256 public initializedTime;
uint256 public finalizedTime;
uint256 public totalInvestedWei;
uint256 public constant IS_TIER_CONTRACT_MAGIC_NUMBER = 0x1337;
modifier notFinished() {
require(finalizedTime == 0);
_;
}
function Tier(
uint256 _cap,
uint256 _minInvestorCap,
uint256 _maxInvestorCap,
uint256 _exchangeRate,
uint256 _startTime,
uint256 _endTime
)
{
require(initializedTime == 0);
assert(_startTime >= getBlockTimestamp());
require(_startTime < _endTime);
startTime = _startTime;
endTime = _endTime;
require(_cap > 0);
require(_cap > _maxInvestorCap);
cap = _cap;
require(_minInvestorCap < _maxInvestorCap && _maxInvestorCap > 0);
minInvestorCap = _minInvestorCap;
maxInvestorCap = _maxInvestorCap;
require(_exchangeRate > 0);
exchangeRate = _exchangeRate;
initializedTime = getBlockTimestamp();
InitializedTier(_cap, _minInvestorCap, maxInvestorCap, _startTime, _endTime);
}
function getBlockTimestamp() internal constant returns (uint256) {
return block.timestamp;
}
function isCapReached() public constant returns(bool) {
return totalInvestedWei == cap;
}
function finalize() public onlyController {
require(finalizedTime == 0);
uint256 currentTime = getBlockTimestamp();
assert(cap == totalInvestedWei || currentTime > endTime || msg.sender == controller);
finalizedTime = currentTime;
}
function increaseInvestedWei(uint256 _wei) external onlyController notFinished {
totalInvestedWei = totalInvestedWei.add(_wei);
IncreaseInvestedWeiAmount(_wei, totalInvestedWei);
}
event InitializedTier(
uint256 _cap,
uint256 _minInvestorCap,
uint256 _maxInvestorCap,
uint256 _startTime,
uint256 _endTime
);
function () public {
require(false);
}
event IncreaseInvestedWeiAmount(uint256 _amount, uint256 _newWei);
}
|
Notifies if an investor is whitelisted for contribution _investor investor address _tier tier Number return number of tokens
|
function isWhitelisted(address _investor, uint256 _tier) public constant returns(bool) {
WhitelistedInvestor memory investor = investors[_investor];
return (investor.tier <= _tier && investor.status);
}
| 931,688
|
//Address: 0x2df77094d9196fa777a2b99934dfb5a3628ea845
//Contract name: TeikhosBounty
//Balance: 0 Ether
//Verification Date: 2/26/2018
//Transacion Count: 3
// CODE STARTS HERE
contract TeikhosBounty {
// Proof-of-public-key in format 2xbytes32, to support xor operator and ecrecover r, s v format
bytes32 proof_of_public_key1 = hex"94cd5137c63cf80cdd176a2a6285572cc076f2fbea67c8b36e65065be7bc34ec";
bytes32 proof_of_public_key2 = hex"9f6463aadf1a8aed68b99aa14538f16d67bf586a4bdecb904d56d5edb2cfb13a";
function authenticate(bytes _publicKey) returns (bool) { // Accepts an array of bytes, for example ["0x00","0xaa", "0xff"]
// Get address from public key
address signer = address(keccak256(_publicKey));
// Split public key in 2xbytes32, to support xor operator and ecrecover r, s v format
bytes32 publicKey1;
bytes32 publicKey2;
assembly {
publicKey1 := mload(add(_publicKey,0x20))
publicKey2 := mload(add(_publicKey,0x40))
}
// Use xor (reverse cipher) to get signature in r, s v format
bytes32 r = proof_of_public_key1 ^ publicKey1;
bytes32 s = proof_of_public_key2 ^ publicKey2;
bytes32 msgHash = keccak256("\x19Ethereum Signed Message:\n64", _publicKey);
// The value v is not known, try both 27 and 28
if(ecrecover(msgHash, 27, r, s) == signer) return true;
if(ecrecover(msgHash, 28, r, s) == signer) return true;
}
}
|
Accepts an array of bytes, for example ["0x00","0xaa", "0xff"]
|
function authenticate(bytes _publicKey) returns (bool) {
| 14,054,035
|
pragma solidity >=0.4.25 <0.6.0;
import "./AdminRole.sol";
import "./openZeppelin/token/ERC721/ERC721MetadataMintable.sol";
import "./openZeppelin/token/ERC721/ERC721Full.sol";
contract IToken {
function mint(address _to) public;
function burn(uint256 tokenId) public;
function getAllUserTokens(address _user) public view returns (uint256[] memory);
}
contract Scissors is IToken, ERC721Full, MinterRole, ERC721MetadataMintable {
uint256 public counter;
mapping(address => uint256[]) public tokensOwned;
constructor() ERC721Full("Scissors", "Scissors") public {}
// Create new tokens
function mint(address _to) public onlyMinter {
uint256 tokenId = counter;
// The third parameter, the tokenURI with all the token metadatas is empty for now until some data is added in the future
mintWithTokenURI(_to, tokenId, "");
counter++;
tokensOwned[_to].push(tokenId);
}
// Burn the specified token
function burn(uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(_isApprovedOrOwner(owner, tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
counter--;
// Find the specific token id and delete it from the array
uint256[] memory userTokens = tokensOwned[owner];
for(uint256 i = 0; i < userTokens.length; i++) {
uint256 tok = userTokens[i];
if (tok == tokenId) {
uint256 lastItem = userTokens[userTokens.length - 1];
tokensOwned[owner][i] = lastItem;
tokensOwned[owner].length--;
break;
}
}
}
// Returns all the user tokens
function getAllUserTokens(address _user) public view returns (uint256[] memory) {
return tokensOwned[_user];
}
}
contract Rocks is IToken, ERC721Full, MinterRole, ERC721MetadataMintable {
uint256 public counter;
mapping(address => uint256[]) public tokensOwned;
constructor() ERC721Full("Rocks", "Rocks") public {}
// Create new tokens
function mint(address _to) public onlyMinter {
uint256 tokenId = counter;
// The third parameter, the tokenURI with all the token metadatas is empty for now until some data is added in the future
mintWithTokenURI(_to, tokenId, "");
counter++;
tokensOwned[_to].push(tokenId);
}
// Burn the specified token
function burn(uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(_isApprovedOrOwner(owner, tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
counter--;
// Find the specific token id and delete it from the array
uint256[] memory userTokens = tokensOwned[owner];
for(uint256 i = 0; i < userTokens.length; i++) {
uint256 tok = userTokens[i];
if (tok == tokenId) {
uint256 lastItem = userTokens[userTokens.length - 1];
tokensOwned[owner][i] = lastItem;
tokensOwned[owner].length--;
break;
}
}
}
// Returns all the user tokens
function getAllUserTokens(address _user) public view returns (uint256[] memory) {
return tokensOwned[_user];
}
}
contract Papers is IToken, ERC721Full, MinterRole, ERC721MetadataMintable {
uint256 public counter;
mapping(address => uint256[]) public tokensOwned;
constructor() ERC721Full("Papers", "Papers") public {}
// Create new tokens
function mint(address _to) public onlyMinter {
uint256 tokenId = counter;
// The third parameter, the tokenURI with all the token metadatas is empty for now until some data is added in the future
mintWithTokenURI(_to, tokenId, "");
counter++;
tokensOwned[_to].push(tokenId);
}
// Burn the specified token
function burn(uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(_isApprovedOrOwner(owner, tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
counter--;
// Find the specific token id and delete it from the array
uint256[] memory userTokens = tokensOwned[owner];
for(uint256 i = 0; i < userTokens.length; i++) {
uint256 tok = userTokens[i];
if (tok == tokenId) {
uint256 lastItem = userTokens[userTokens.length - 1];
tokensOwned[owner][i] = lastItem;
tokensOwned[owner].length--;
break;
}
}
}
// Returns all the user tokens
function getAllUserTokens(address _user) public view returns (uint256[] memory) {
return tokensOwned[_user];
}
}
contract Stars is IToken, ERC721Full, MinterRole, ERC721MetadataMintable {
uint256 public counter;
mapping(address => uint256[]) public tokensOwned;
constructor() ERC721Full("Stars", "Stars") public {}
// Create new tokens
function mint(address _to) public onlyMinter {
uint256 tokenId = counter;
// The third parameter, the tokenURI with all the token metadatas is empty for now until some data is added in the future
mintWithTokenURI(_to, tokenId, "");
counter++;
tokensOwned[_to].push(tokenId);
}
// Burn the specified token
function burn(uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(_isApprovedOrOwner(owner, tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
counter--;
// Find the specific token id and delete it from the array
uint256[] memory userTokens = tokensOwned[owner];
for(uint256 i = 0; i < userTokens.length; i++) {
uint256 tok = userTokens[i];
if (tok == tokenId) {
uint256 lastItem = userTokens[userTokens.length - 1];
tokensOwned[owner][i] = lastItem;
tokensOwned[owner].length--;
break;
}
}
}
// Returns all the user tokens
function getAllUserTokens(address _user) public view returns (uint256[] memory) {
return tokensOwned[_user];
}
}
contract Game is AdminRole {
event SeeValue(uint256 val, string des);
event Msg(string des);
struct LeagueInfo {
uint256 maxNumberOfRocks;
uint256 maxNumberOfScissors;
uint256 maxNumberOfPapers;
uint256 maxNumberOfStars;
uint256 currentRocksAvailable; // These are 0 by default
uint256 currentPapersAvailable;
uint256 currentScissorsAvailable;
uint256 currentStarsAvailable;
uint256 rocksUsed; // The maximum minus the deleted ones after placing
uint256 papersUsed;
uint256 scissorsUsed;
}
//LeagueId => LeagueInfo
LeagueInfo[] public leagues;
uint256 public cardPrice = 10 trx; // Each card costs 10 TRX
IToken public rockToken;
IToken public scissorToken;
IToken public paperToken;
IToken public starToken;
address payable public owner;
constructor(
address _rockToken,
address _scissorsToken,
address _paperToken,
address _starToken
) public {
rockToken = IToken(_rockToken);
scissorToken = IToken(_scissorsToken);
paperToken = IToken(_paperToken);
starToken = IToken(_starToken);
owner = msg.sender;
}
function addLeague(uint256 _numberOfRocks, uint256 _numberOfScissors, uint256 _numberOfPapers, uint256 _numberOfStars) public onlyAdmin {
LeagueInfo memory leagueInfo;
leagueInfo.maxNumberOfRocks = _numberOfRocks;
leagueInfo.maxNumberOfScissors = _numberOfScissors;
leagueInfo.maxNumberOfPapers = _numberOfPapers;
leagueInfo.maxNumberOfStars = _numberOfStars;
leagueInfo.rocksUsed = _numberOfRocks;
leagueInfo.scissorsUsed = _numberOfScissors;
leagueInfo.papersUsed = _numberOfPapers;
leagues.push(leagueInfo);
}
function getLeagueInfoById(uint256 _leagueId) public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
return (
leagues[_leagueId].maxNumberOfRocks,
leagues[_leagueId].maxNumberOfScissors,
leagues[_leagueId].maxNumberOfPapers,
leagues[_leagueId].maxNumberOfStars,
leagues[_leagueId].currentRocksAvailable,
leagues[_leagueId].currentPapersAvailable,
leagues[_leagueId].currentScissorsAvailable);
}
// Gives the cards available in the league after usage to show in the gameplay
function getRemainingCardsInLeague() public view returns (uint256, uint256, uint256) {
require(leagues.length > 0, "There are no leagues available right now");
LeagueInfo memory currentLeague = leagues[leagues.length - 1];
return (
currentLeague.rocksUsed,
currentLeague.papersUsed,
currentLeague.scissorsUsed
);
}
// Returns the in use papers, rocks and scissors or throws if no league exists
function getLatestLeagueInfo() public view returns (uint256, uint256, uint256) {
require(leagues.length > 0, "There are no leagues available right now");
LeagueInfo memory currentLeague = leagues[leagues.length - 1];
return (
currentLeague.currentRocksAvailable,
currentLeague.currentPapersAvailable,
currentLeague.currentScissorsAvailable
);
}
function getAvailableTokensForPurchase() public view returns(uint256) {
LeagueInfo memory currentLeague = leagues[leagues.length - 1];
return currentLeague.maxNumberOfRocks - currentLeague.currentRocksAvailable + currentLeague.maxNumberOfPapers - currentLeague.currentPapersAvailable + currentLeague.maxNumberOfScissors - currentLeague.currentScissorsAvailable;
}
function buyRocks(uint256 _cardsToBuy) public payable {
require(msg.value >= _cardsToBuy * cardPrice, "You must send the right price price for the amount of cards you want to buy");
require(leagues.length > 0, "There are no leagues available right now");
require(leagues[leagues.length - 1].currentRocksAvailable < leagues[leagues.length - 1].maxNumberOfRocks, "No rocks available for purchase in this league anymore");
for (uint256 i = 0; i < _cardsToBuy; i++) {
rockToken.mint(msg.sender);
leagues[leagues.length - 1].currentRocksAvailable++;
}
}
function buyPapers(uint256 _cardsToBuy) public payable {
require(msg.value >= _cardsToBuy * cardPrice, "You must send the right price price for the amount of cards you want to buy");
require(leagues.length > 0, "There are no leagues available right now");
require(leagues[leagues.length - 1].currentPapersAvailable < leagues[leagues.length - 1].maxNumberOfPapers, "No papers available for purchase in this league anymore");
for (uint256 i = 0; i < _cardsToBuy; i++) {
paperToken.mint(msg.sender);
leagues[leagues.length - 1].currentPapersAvailable++;
}
}
function buyScissors(uint256 _cardsToBuy) public payable {
require(msg.value >= _cardsToBuy * cardPrice, "You must send the right price price for the amount of cards you want to buy");
require(leagues.length > 0, "There are no leagues available right now");
require(leagues[leagues.length - 1].currentScissorsAvailable < leagues[leagues.length - 1].maxNumberOfScissors, "No scissors available for purchase in this league anymore");
for (uint256 i = 0; i < _cardsToBuy; i++) {
scissorToken.mint(msg.sender);
leagues[leagues.length - 1].currentScissorsAvailable++;
}
}
// You need to send the msg.value where each card is 10 TRX so if you
// set the quantity to 20, you must send 200 TRX or more
// if you send more than the quantity, you lost that amount
function buyCards(uint256 _cardsToBuy) public payable {
emit Msg('1');
require(msg.value >= _cardsToBuy * cardPrice, "You must send the right price price for the amount of cards you want to buy");
emit Msg('2');
require(leagues.length > 0, "There are no leagues available right now");
emit Msg('3');
require(getAvailableTokensForPurchase() > 0, "There are no tokens available for purchase on this league anymore");
emit Msg('4');
uint8 lastId = 0;
// Mint the required tokens for each type alternating
for (uint256 i = 0; i < _cardsToBuy; i++) {
emit Msg('5');
if (lastId == 0) {
if (leagues[leagues.length - 1].currentRocksAvailable < leagues[leagues.length - 1].maxNumberOfRocks) {
mintRocks();
} else if (leagues[leagues.length - 1].currentPapersAvailable < leagues[leagues.length - 1].maxNumberOfPapers) {
mintPapers();
} else if (leagues[leagues.length - 1].currentScissorsAvailable < leagues[leagues.length - 1].maxNumberOfScissors) {
mintScissors();
} else {
// No more cards available anymore
break;
}
} else if (lastId == 1) {
emit Msg('6');
if (leagues[leagues.length - 1].currentPapersAvailable < leagues[leagues.length - 1].maxNumberOfPapers) {
mintPapers();
} else if (leagues[leagues.length - 1].currentRocksAvailable < leagues[leagues.length - 1].maxNumberOfRocks) {
mintRocks();
} else if (leagues[leagues.length - 1].currentScissorsAvailable < leagues[leagues.length - 1].maxNumberOfScissors) {
mintScissors();
} else {
// No more cards available anymore
break;
}
} else {
emit Msg('7');
if (leagues[leagues.length - 1].currentScissorsAvailable < leagues[leagues.length - 1].maxNumberOfScissors) {
mintScissors();
} else if (leagues[leagues.length - 1].currentPapersAvailable < leagues[leagues.length - 1].maxNumberOfPapers) {
mintPapers();
} else if (leagues[leagues.length - 1].currentRocksAvailable < leagues[leagues.length - 1].maxNumberOfRocks) {
mintRocks();
} else {
// No more cards available anymore
break;
}
}
emit Msg('8');
if (lastId == 2) lastId = 0;
else lastId++;
}
}
// Returns the array of owned card for each type
function getMyCards() public view returns(uint256[] memory, uint256[] memory, uint256[] memory) {
uint256[] memory rocks = rockToken.getAllUserTokens(msg.sender);
uint256[] memory papers = paperToken.getAllUserTokens(msg.sender);
uint256[] memory scissors = scissorToken.getAllUserTokens(msg.sender);
return (rocks, papers, scissors);
}
function mintRocks() internal {
rockToken.mint(msg.sender);
leagues[leagues.length - 1].currentRocksAvailable++;
}
function mintPapers() internal {
paperToken.mint(msg.sender);
leagues[leagues.length - 1].currentPapersAvailable++;
}
function mintScissors() internal {
scissorToken.mint(msg.sender);
leagues[leagues.length - 1].currentScissorsAvailable++;
}
function deleteCard(string memory _cardType) public {
uint256[] memory userRocks;
uint256[] memory userPapers;
uint256[] memory userScissors;
(userRocks, userPapers, userScissors) = getMyCards();
LeagueInfo memory currentLeague = leagues[leagues.length - 1];
require(currentLeague.rocksUsed > 0
&& currentLeague.papersUsed > 0
&& currentLeague.scissorsUsed > 0, "No cards available for deletion");
if (keccak256(abi.encode(_cardType)) == keccak256(abi.encode("Rock"))
&& userRocks.length > 0) {
rockToken.burn(userRocks[0]);
leagues[leagues.length - 1].rocksUsed -= 1;
} else if (keccak256(abi.encode(_cardType)) == keccak256(abi.encode("Paper"))
&& userPapers.length > 0) {
paperToken.burn(userPapers[0]);
leagues[leagues.length - 1].papersUsed -= 1;
} else if (keccak256(abi.encode(_cardType)) == keccak256(abi.encode("Scissors"))
&& userScissors.length > 0) {
scissorToken.burn(userScissors[0]);
leagues[leagues.length - 1].scissorsUsed -= 1;
}
}
function extractFunds() public {
require(msg.sender == owner);
owner.transfer(address(this).balance);
}
}
|
Returns the array of owned card for each type
|
function getMyCards() public view returns(uint256[] memory, uint256[] memory, uint256[] memory) {
uint256[] memory rocks = rockToken.getAllUserTokens(msg.sender);
uint256[] memory papers = paperToken.getAllUserTokens(msg.sender);
uint256[] memory scissors = scissorToken.getAllUserTokens(msg.sender);
return (rocks, papers, scissors);
}
| 992,545
|
./full_match/97/0xccb4651211dE317551C38ED499c4e09d56F604dc/sources/project_/contracts/piMarket.sol
|
cancle swap by initiator
|
function cancelSwap(uint256 _swapId) public nonReentrant {
require(
msg.sender == _swaps[_swapId].initiator,
"Only owner can cancel sale"
);
require(_swaps[_swapId].status, "Token not on swap");
_swaps[_swapId].status = false;
ERC721(_swaps[_swapId].initiatorNFTAddress).safeTransferFrom(
address(this),
_swaps[_swapId].initiator,
_swaps[_swapId].initiatorNftId
);
emit SwapCancelled(_swapId);
}
| 3,276,776
|
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/AssetHelpers.sol";
import "./Moartroller.sol";
import "./SimplePriceOracle.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers {
/**
* @notice get the maximum asset value that can be still optimized.
* @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value'
* which is helpful to recalculate how much of this protection can be optimized again
*/
function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){
uint returnValue;
uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments);
uint totalProtectionLockedValue;
(totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments);
if(hypotheticalOptimizableValue <= totalProtectionLockedValue){
returnValue = 0;
}
else{
returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue);
}
return returnValue;
}
/**
* @notice get the maximum value of an asset that can be optimized by protection for the given user
* @dev optimizable = asset value * MPC
* @return the hypothetical optimizable value
* TODO: replace hardcoded 1e18 values
*/
function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) {
uint assetValue = div_(
mul_(
div_(
mul_(
arguments.asset.balanceOf(arguments.account),
arguments.asset.exchangeRateStored()
),
1e18
),
arguments.oracle.getUnderlyingPrice(arguments.asset)
),
getAssetDecimalsMantissa(arguments.asset.getUnderlying())
);
uint256 hypotheticalOptimizableValue = div_(
mul_(
assetValue,
arguments.asset.maxProtectionComposition()
),
arguments.asset.maxProtectionCompositionMantissa()
);
return hypotheticalOptimizableValue;
}
/**
* @dev gets all locked protections values with mark to market value. Used by Moartroller.
*/
function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) {
uint _lockedValue = 0;
uint _markToMarket = 0;
uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying());
for (uint j = 0; j < _protectionCount; j++) {
uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j);
bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId);
if(protectionIsAlive){
_lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId));
uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset);
uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId);
if( assetSpotPrice > protectionStrikePrice) {
_markToMarket = _markToMarket + div_(
mul_(
div_(
mul_(
assetSpotPrice - protectionStrikePrice,
arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId)
),
getAssetDecimalsMantissa(arguments.asset.underlying())
),
arguments.collateralFactorMantissa
),
1e18
);
}
}
}
return (_lockedValue , _markToMarket);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../MProtection.sol";
import "../Interfaces/PriceOracle.sol";
interface LiquidityMathModelInterface {
struct LiquidityMathArgumentsSet {
MToken asset;
address account;
uint collateralFactorMantissa;
MProtection cprotection;
PriceOracle oracle;
}
function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint);
function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint);
function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Utils/ErrorReporter.sol";
import "./Utils/Exponential.sol";
import "./Interfaces/EIP20Interface.sol";
import "./MTokenStorage.sol";
import "./Interfaces/MTokenInterface.sol";
import "./Interfaces/MProxyInterface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
/**
* @title MOAR's MToken Contract
* @notice Abstract base for MTokens
* @author MOAR
*/
abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage {
/**
* @notice Indicator that this is a MToken contract (for inspection)
*/
bool public constant isMToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address MTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when moartroller is changed
*/
event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @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);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/**
* @notice Max protection composition value updated event
*/
event MpcUpdated(uint newValue);
/**
* @notice Initialize the money market
* @param moartroller_ The address of the Moartroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function init(Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "not_admin");
require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "too_low");
// Set the moartroller
uint err = _setMoartroller(moartroller_);
require(err == uint(Error.NO_ERROR), "setting moartroller failed");
// Initialize block number and borrow index (block number mocks depend on moartroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting IRM failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
maxProtectionComposition = 5000;
maxProtectionCompositionMantissa = 1e4;
reserveFactorMaxMantissa = 1e18;
borrowRateMaxMantissa = 0.0005e16;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = moartroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srmTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srmTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srmTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
// unused function
// moartroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external virtual override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external virtual override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external virtual override returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external virtual override view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external virtual override view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external virtual override returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance_calculation_failed");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by moartroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external virtual override view returns (uint, uint, uint, uint) {
uint mTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), mTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this mToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this mToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external virtual override view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external virtual override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external virtual override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public virtual view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public virtual nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public virtual view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the MToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this mToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external virtual override view returns (uint) {
return getCashPrior();
}
function getRealBorrowIndex() public view returns (uint) {
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
Exp memory simpleInterestFactor;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor");
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex");
return borrowIndexNew;
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public virtual returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calc block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
AccrueInterestTempStorage memory temp;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior);
if(mathErr != MathError.NO_ERROR){
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, temp.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = temp.borrowIndexNew;
totalBorrows = temp.totalBorrowsNew;
totalReserves = temp.totalReservesNew;
if(temp.splitedReserves_2 > 0){
address mProxy = moartroller.mProxy();
EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2);
MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2);
}
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives mTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives mTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = moartroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the mToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of mTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/*
* We calculate the new total supply of mTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_E");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
// unused function
// moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems mTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming mTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems mTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/* Fail if user tries to redeem more than he has locked with c-op*/
// TODO: update error codes
uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18);
if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) {
require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing");
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(borrower, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = moartroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
//unused function
// moartroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
/* If the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */
if (repayAmount == uint(-1)) {
require(tx.origin == borrower, "specify a precise amount");
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// moartroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, MToken mTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = mTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, mTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, MToken mTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify mTokenCollateral market's block number equals current block number */
if (mTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower);
require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(mTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = mTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(mTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another mToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external virtual override nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another MToken.
* Its absolutely critical to use msg.sender as the seizer mToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed mToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of mTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
// unused function
// moartroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external virtual override returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external virtual override returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new moartroller for the market
* @dev Admin function to set a new moartroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK);
}
Moartroller oldMoartroller = moartroller;
// Ensure invoke moartroller.isMoartroller() returns true
require(newMoartroller.isMoartroller(), "not_moartroller");
// Set market's moartroller to newMoartroller
moartroller = newMoartroller;
// Emit NewMoartroller(oldMoartroller, newMoartroller)
emit NewMoartroller(oldMoartroller, newMoartroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external virtual override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
reserveSplitFactorMantissa = newReserveSplitFactorMantissa;
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The mToken must handle variations between ERC-20 and ETH underlying.
* On success, the mToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external virtual override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(AbstractInterestRateModel newInterestRateModel) public virtual returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(AbstractInterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModelInterface oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "not_interest_model");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets new value for max protection composition parameter
* @param newMPC New value of MPC
* @return uint 0=success, otherwise a failure
*/
function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
maxProtectionComposition = newMPC;
emit MpcUpdated(newMPC);
return uint(Error.NO_ERROR);
}
/**
* @notice Returns address of underlying token
* @return address of underlying token
*/
function getUnderlying() external override view returns(address){
return underlying;
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal virtual view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal virtual returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal virtual;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
contract MoartrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
MOARTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SUPPORT_PROTECTION_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
MOARTROLLER_REJECTION,
MOARTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_MOARTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_MOARTROLLER_REJECTION,
LIQUIDATE_MOARTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_MOARTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_MOARTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_MOARTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_MOARTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_MOARTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_MOARTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract LiquidityMathModelErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
PRICE_ERROR,
SNAPSHOT_ERROR
}
enum FailureInfo {
ORACLE_PRICE_CHECK_FAILED
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Exponential module for storing fixed-precision decimals
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../Interfaces/EIP20Interface.sol";
contract AssetHelpers {
/**
* @dev return asset decimals mantissa. Returns 1e18 if ETH
*/
function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){
uint assetDecimals = 1e18;
if (assetAddress != address(0)) {
EIP20Interface token = EIP20Interface(assetAddress);
assetDecimals = 10 ** uint256(token.decimals());
}
return assetDecimals;
}
}
// SPDX-License-Identifier: BSD-3-Clause
// Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon.
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "./MToken.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/ExponentialNoError.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/MoartrollerInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Interfaces/MProxyInterface.sol";
import "./MoartrollerStorage.sol";
import "./Governance/UnionGovernanceToken.sol";
import "./MProtection.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./LiquidityMathModelV1.sol";
import "./Utils/SafeEIP20.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title MOAR's Moartroller Contract
* @author MOAR
*/
contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable {
using SafeEIP20 for EIP20Interface;
/// @notice Indicator that this is a Moartroller contract (for inspection)
bool public constant isMoartroller = true;
/// @notice Emitted when an admin supports a market
event MarketListed(MToken mToken);
/// @notice Emitted when an account enters a market
event MarketEntered(MToken mToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(MToken mToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when protection is changed
event NewCProtection(MProtection oldCProtection, MProtection newCProtection);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPausedMToken(MToken mToken, string action, bool pauseState);
/// @notice Emitted when a new MOAR speed is calculated for a market
event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed);
/// @notice Emitted when a new MOAR speed is set for a contributor
event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed);
/// @notice Emitted when MOAR is distributed to a supplier
event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex);
/// @notice Emitted when MOAR is distributed to a borrower
event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex);
/// @notice Emitted when borrow cap for a mToken is changed
event NewBorrowCap(MToken indexed mToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when MOAR is granted by admin
event MoarGranted(address recipient, uint amount);
event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel);
event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel);
/// @notice The initial MOAR index for a market
uint224 public constant moarInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// Custom initializer
function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer {
admin = msg.sender;
liquidityMathModel = mathModel;
liquidationModel = lqdModel;
rewardClaimEnabled = false;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (MToken[] memory) {
MToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param mToken The mToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, MToken mToken) external view returns (bool) {
return markets[address(mToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param mTokens The list of addresses of the mToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) {
uint len = mTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
MToken mToken = MToken(mTokens[i]);
results[i] = uint(addToMarketInternal(mToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param mToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(mToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(mToken);
emit MarketEntered(mToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param mTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address mTokenAddress) external override returns (uint) {
MToken mToken = MToken(mTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the mToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(mToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set mToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete mToken from the account’s list of assets */
// load into memory for faster iteration
MToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == mToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
MToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(mToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param mToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[mToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param mToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of mTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) {
uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[mToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param mToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {
// Shh - currently unused
mToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param mToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[mToken], "borrow is paused");
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[mToken].accountMembership[borrower]) {
// only mTokens may call borrowAllowed if borrower not in market
require(msg.sender == mToken, "sender must be mToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(MToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[mToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[mToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = MToken(mToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param mToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()});
updateMoarBorrowIndex(mToken, borrowIndex);
distributeBorrowerMoar(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) {
return uint(Error.MOARTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateMoarSupplyIndex(mTokenCollateral);
distributeSupplierMoar(mTokenCollateral, borrower);
distributeSupplierMoar(mTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param mToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of mTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(mToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateMoarSupplyIndex(mToken);
distributeSupplierMoar(mToken, src);
distributeSupplierMoar(mToken, dst);
return uint(Error.NO_ERROR);
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address mTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
MToken mTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
MToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
MToken asset = assets[i];
address _account = account;
// Read the balances and exchange rate from the mToken
(oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals()));
// Pre-compute a conversion factor from tokens -> dai (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * mTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral);
// Protection value calculation sumCollateral += protectionValueLocked
// Mark to market value calculation sumCollateral += markToMarketValue
uint protectionValueLocked;
uint markToMarketValue;
(protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle));
if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) {
vars.sumCollateral = 0;
} else {
vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor));
}
vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked);
vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with mTokenModify
if (asset == mTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
_account = account;
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Returns the value of possible optimization left for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The value of possible optimization
*/
function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getMaxOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
/**
* @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of hypothetical optimization
*/
function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){
return liquidityMathModel.getHypotheticalOptimizableValue(
LiquidityMathModelInterface.LiquidityMathArgumentsSet(
asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle
)
);
}
function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) {
return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens(
LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet(
oracle,
this,
mTokenBorrowed,
mTokenCollateral,
actualRepayAmount,
account,
liquidationIncentiveMantissa
)
);
}
/**
* @notice Returns the amount of a specific asset that is locked under all c-ops
* @param asset The MToken address
* @param account The owner of asset
* @return The amount of asset locked under c-ops
*/
function getUserLockedAmount(MToken asset, address account) public override view returns(uint) {
uint protectionLockedAmount;
address currency = asset.underlying();
uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency);
for (uint i = 0; i < numOfProtections; i++) {
uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i);
if(cprotection.isProtectionAlive(cProtectionId)){
protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId);
}
}
return protectionLockedAmount;
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the moartroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the moartroller
PriceOracle oldOracle = oracle;
// Set moartroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new CProtection that is allowed to use as a collateral optimisation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setProtection(address newCProtection) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
MProtection oldCProtection = cprotection;
cprotection = MProtection(newCProtection);
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewCProtection(oldCProtection, cprotection);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param mToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(mToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
// TODO: this check is temporary switched off. we can make exception for UNN later
// Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
//
//
// Check collateral factor <= 0.9
// Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
// if (lessThanExp(highLimit, newCollateralFactorExp)) {
// return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
// }
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
function _setRewardClaimEnabled(bool status) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
rewardClaimEnabled = status;
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param mToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(MToken mToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(mToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
mToken.isMToken(); // Sanity check to make sure its really a MToken
// Note that isMoared is not in active use anymore
markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0});
tokenAddressToMToken[address(mToken.underlying())] = mToken;
_addMarketInternal(address(mToken));
emit MarketListed(mToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address mToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != MToken(mToken), "market already added");
}
allMarkets.push(MToken(mToken));
}
/**
* @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param mTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps");
uint numMarkets = mTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(mTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(mTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Mint", state);
return state;
}
function _setBorrowPaused(MToken mToken, bool state) public returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(mToken)] = state;
emit ActionPausedMToken(mToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == moartrollerImplementation;
}
/*** MOAR Distribution ***/
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal {
uint currentMoarSpeed = moarSpeeds[address(mToken)];
if (currentMoarSpeed != 0) {
// note that MOAR speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarSupplyIndex(address(mToken));
updateMoarBorrowIndex(address(mToken), borrowIndex);
} else if (moarSpeed != 0) {
// Add the MOAR market
Market storage market = markets[address(mToken)];
require(market.isListed == true, "MOAR market is not listed");
if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) {
moarSupplyState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) {
moarBorrowState[address(mToken)] = MoarMarketState({
index: moarInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
if (currentMoarSpeed != moarSpeed) {
moarSpeeds[address(mToken)] = moarSpeed;
emit MoarSpeedUpdated(mToken, moarSpeed);
}
}
/**
* @notice Accrue MOAR to the market by updating the supply index
* @param mToken The market whose supply index to update
*/
function updateMoarSupplyIndex(address mToken) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
uint supplySpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = MToken(mToken).totalSupply();
uint moarAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
moarSupplyState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue MOAR to the market by updating the borrow index
* @param mToken The market whose borrow index to update
*/
function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
uint borrowSpeed = moarSpeeds[mToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex);
uint moarAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
moarBorrowState[mToken] = MoarMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate MOAR accrued by a supplier and possibly transfer it to them
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute MOAR to
*/
function distributeSupplierMoar(address mToken, address supplier) internal {
MoarMarketState storage supplyState = moarSupplyState[mToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]});
moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = moarInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = MToken(mToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta);
moarAccrued[supplier] = supplierAccrued;
emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate MOAR accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOAR to
*/
function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal {
MoarMarketState storage borrowState = moarBorrowState[mToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]});
moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta);
moarAccrued[borrower] = borrowerAccrued;
emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Calculate additional accrued MOAR for a contributor since last accrual
* @param contributor The address to calculate contributor rewards for
*/
function updateContributorRewards(address contributor) public {
uint moarSpeed = moarContributorSpeeds[contributor];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]);
if (deltaBlocks > 0 && moarSpeed > 0) {
uint newAccrued = mul_(deltaBlocks, moarSpeed);
uint contributorAccrued = add_(moarAccrued[contributor], newAccrued);
moarAccrued[contributor] = contributorAccrued;
lastContributorBlock[contributor] = blockNumber;
}
}
/**
* @notice Claim all the MOAR accrued by holder in all markets
* @param holder The address to claim MOAR for
*/
function claimMoarReward(address holder) public {
return claimMoar(holder, allMarkets);
}
/**
* @notice Claim all the MOAR accrued by holder in the specified markets
* @param holder The address to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
*/
function claimMoar(address holder, MToken[] memory mTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimMoar(holders, mTokens, true, true);
}
/**
* @notice Claim all MOAR accrued by the holders
* @param holders The addresses to claim MOAR for
* @param mTokens The list of markets to claim MOAR in
* @param borrowers Whether or not to claim MOAR earned by borrowing
* @param suppliers Whether or not to claim MOAR earned by supplying
*/
function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public {
require(rewardClaimEnabled, "reward claim is disabled");
for (uint i = 0; i < mTokens.length; i++) {
MToken mToken = mTokens[i];
require(markets[address(mToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()});
updateMoarBorrowIndex(address(mToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerMoar(address(mToken), holders[j], borrowIndex);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
if (suppliers == true) {
updateMoarSupplyIndex(address(mToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierMoar(address(mToken), holders[j]);
moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]);
}
}
}
}
/**
* @notice Transfer MOAR to the user
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param user The address of the user to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
* @return The amount of MOAR which was NOT transferred to the user
*/
function grantMoarInternal(address user, uint amount) internal returns (uint) {
EIP20Interface moar = EIP20Interface(getMoarAddress());
uint moarRemaining = moar.balanceOf(address(this));
if (amount > 0 && amount <= moarRemaining) {
moar.approve(mProxy, amount);
MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount);
return 0;
}
return amount;
}
/*** MOAR Distribution Admin ***/
/**
* @notice Transfer MOAR to the recipient
* @dev Note: If there is not enough MOAR, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer MOAR to
* @param amount The amount of MOAR to (possibly) transfer
*/
function _grantMoar(address recipient, uint amount) public {
require(adminOrInitializing(), "only admin can grant MOAR");
uint amountLeft = grantMoarInternal(recipient, amount);
require(amountLeft == 0, "insufficient MOAR for grant");
emit MoarGranted(recipient, amount);
}
/**
* @notice Set MOAR speed for a single market
* @param mToken The market whose MOAR speed to update
* @param moarSpeed New MOAR speed for market
*/
function _setMoarSpeed(MToken mToken, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
setMoarSpeedInternal(mToken, moarSpeed);
}
/**
* @notice Set MOAR speed for a single contributor
* @param contributor The contributor whose MOAR speed to update
* @param moarSpeed New MOAR speed for contributor
*/
function _setContributorMoarSpeed(address contributor, uint moarSpeed) public {
require(adminOrInitializing(), "only admin can set MOAR speed");
// note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor
updateContributorRewards(contributor);
if (moarSpeed == 0) {
// release storage
delete lastContributorBlock[contributor];
} else {
lastContributorBlock[contributor] = getBlockNumber();
}
moarContributorSpeeds[contributor] = moarSpeed;
emit ContributorMoarSpeedUpdated(contributor, moarSpeed);
}
/**
* @notice Set liquidity math model implementation
* @param mathModel the math model implementation
*/
function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel;
liquidityMathModel = mathModel;
emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel));
}
/**
* @notice Set liquidation model implementation
* @param newLiquidationModel the liquidation model implementation
*/
function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public {
require(msg.sender == admin, "only admin can set liquidation model implementation");
LiquidationModelInterface oldLiquidationModel = liquidationModel;
liquidationModel = newLiquidationModel;
emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel));
}
function _setMoarToken(address moarTokenAddress) public {
require(msg.sender == admin, "only admin can set MOAR token address");
moarToken = moarTokenAddress;
}
function _setMProxy(address mProxyAddress) public {
require(msg.sender == admin, "only admin can set MProxy address");
mProxy = mProxyAddress;
}
/**
* @notice Add new privileged address
* @param privilegedAddress address to add
*/
function _addPrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
privilegedAddresses[privilegedAddress] = 1;
}
/**
* @notice Remove privileged address
* @param privilegedAddress address to remove
*/
function _removePrivilegedAddress(address privilegedAddress) public {
require(msg.sender == admin, "only admin can set liquidity math model implementation");
delete privilegedAddresses[privilegedAddress];
}
/**
* @notice Check if address if privileged
* @param privilegedAddress address to check
*/
function isPrivilegedAddress(address privilegedAddress) public view returns (bool) {
return privilegedAddresses[privilegedAddress] == 1;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (MToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the MOAR token
* @return The address of MOAR
*/
function getMoarAddress() public view returns (address) {
return moarToken;
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/PriceOracle.sol";
import "./CErc20.sol";
/**
* Temporary simple price feed
*/
contract SimplePriceOracle is PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
mapping(address => uint) prices;
event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa);
function getUnderlyingPrice(MToken mToken) public override view returns (uint) {
if (compareStrings(mToken.symbol(), "mDAI")) {
return 1e18;
} else {
return prices[address(MErc20(address(mToken)).underlying())];
}
}
function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public {
address asset = address(MErc20(address(mToken)).underlying());
emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);
prices[asset] = underlyingPriceMantissa;
}
function setDirectPrice(address asset, uint price) public {
emit PricePosted(asset, prices[asset], price, price);
prices[asset] = price;
}
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) {
return prices[asset];
}
function compareStrings(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "./Interfaces/CopMappingInterface.sol";
import "./Interfaces/Versionable.sol";
import "./Moartroller.sol";
import "./Utils/ExponentialNoError.sol";
import "./Utils/ErrorReporter.sol";
import "./Utils/AssetHelpers.sol";
import "./MToken.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MProtection Contract
* @notice Collateral optimization ERC-721 wrapper
* @author MOAR
*/
contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable {
using Counters for Counters.Counter;
using EnumerableSet for EnumerableSet.UintSet;
/**
* @notice Event emitted when new MProtection token is minted
*/
event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime);
/**
* @notice Event emitted when MProtection token is redeemed
*/
event Redeem(address redeemer, uint tokenId, uint underlyingTokenId);
/**
* @notice Event emitted when MProtection token changes its locked value
*/
event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue);
/**
* @notice Event emitted when maturity window parameter is changed
*/
event MaturityWindowUpdated(uint newMaturityWindow);
Counters.Counter private _tokenIds;
address private _copMappingAddress;
address private _moartrollerAddress;
mapping (uint256 => uint256) private _underlyingProtectionTokensMapping;
mapping (uint256 => uint256) private _underlyingProtectionLockedValue;
mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping;
uint256 public _maturityWindow;
struct ProtectionMappedData{
address pool;
address underlyingAsset;
uint256 amount;
uint256 strike;
uint256 premium;
uint256 lockedValue;
uint256 totalValue;
uint issueTime;
uint expirationTime;
bool isProtectionAlive;
}
/**
* @notice Constructor for MProtection contract
* @param copMappingAddress The address of data mapper for C-OP
* @param moartrollerAddress The address of the Moartroller
*/
function initialize(address copMappingAddress, address moartrollerAddress) public initializer {
__Ownable_init();
__ERC721_init("c-uUNN OC-Protection", "c-uUNN");
_copMappingAddress = copMappingAddress;
_moartrollerAddress = moartrollerAddress;
_setMaturityWindow(10800); // 3 hours default
}
/**
* @notice Returns C-OP mapping contract
*/
function copMapping() private view returns (CopMappingInterface){
return CopMappingInterface(_copMappingAddress);
}
/**
* @notice Mint new MProtection token
* @param underlyingTokenId Id of C-OP token that will be deposited
* @return ID of minted MProtection token
*/
function mint(uint256 underlyingTokenId) public returns (uint256)
{
return mintFor(underlyingTokenId, msg.sender);
}
/**
* @notice Mint new MProtection token for specified address
* @param underlyingTokenId Id of C-OP token that will be deposited
* @param receiver Address that will receive minted Mprotection token
* @return ID of minted MProtection token
*/
function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256)
{
CopMappingInterface copMappingInstance = copMapping();
ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId);
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(receiver, newItemId);
addUProtectionIndexes(receiver, newItemId, underlyingTokenId);
emit Mint(
receiver,
newItemId,
underlyingTokenId,
copMappingInstance.getUnderlyingAsset(underlyingTokenId),
copMappingInstance.getUnderlyingAmount(underlyingTokenId),
copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId),
copMappingInstance.getUnderlyingDeadline(underlyingTokenId)
);
return newItemId;
}
/**
* @notice Redeem C-OP token
* @param tokenId Id of MProtection token that will be withdrawn
* @return ID of redeemed C-OP token
*/
function redeem(uint256 tokenId) external returns (uint256) {
require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved");
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId);
removeProtectionIndexes(tokenId);
_burn(tokenId);
emit Redeem(msg.sender, tokenId, underlyingTokenId);
return underlyingTokenId;
}
/**
* @notice Returns set of C-OP data
* @param tokenId Id of MProtection token
* @return ProtectionMappedData struct filled with C-OP data
*/
function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){
ProtectionMappedData memory data;
(address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId);
data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId));
return data;
}
/**
* @notice Returns underlying token ID
* @param tokenId Id of MProtection token
*/
function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){
return _underlyingProtectionTokensMapping[tokenId];
}
/**
* @notice Returns size of C-OPs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].length();
}
/**
* @notice Returns list of C-OP IDs filtered by asset address
* @param owner Address of wallet holding C-OPs
* @param currency Address of asset used to filter C-OPs
*/
function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){
return _protectionCurrencyMapping[owner][currency].at(index);
}
/**
* @notice Checks if address is owner of MProtection
* @param owner Address of potential owner to check
* @param tokenId ID of MProtection to check
*/
function isUserProtection(address owner, uint256 tokenId) public view returns(bool) {
if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){
return true;
}
return owner == ownerOf(tokenId);
}
/**
* @notice Checks if MProtection is stil alive
* @param tokenId ID of MProtection to check
*/
function isProtectionAlive(uint256 tokenId) public view returns(bool) {
uint256 deadline = getUnderlyingDeadline(tokenId);
return (deadline - _maturityWindow) > now;
}
/**
* @notice Creates appropriate indexes for C-OP
* @param owner C-OP owner address
* @param tokenId ID of MProtection
* @param underlyingTokenId ID of C-OP
*/
function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{
address currency = copMapping().getUnderlyingAsset(underlyingTokenId);
_underlyingProtectionTokensMapping[tokenId] = underlyingTokenId;
_protectionCurrencyMapping[owner][currency].add(tokenId);
}
/**
* @notice Remove indexes for C-OP
* @param tokenId ID of MProtection
*/
function removeProtectionIndexes(uint256 tokenId) private{
address owner = ownerOf(tokenId);
address currency = getUnderlyingAsset(tokenId);
_underlyingProtectionTokensMapping[tokenId] = 0;
_protectionCurrencyMapping[owner][currency].remove(tokenId);
}
/**
* @notice Returns C-OP total value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
return div_(
mul_(
getUnderlyingStrikePrice(tokenId),
getUnderlyingAmount(tokenId)
),
assetDecimalsMantissa
);
}
/**
* @notice Returns C-OP locked value
* @param tokenId ID of MProtection
*/
function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){
return _underlyingProtectionLockedValue[tokenId];
}
/**
* @notice get the amount of underlying asset that is locked
* @param tokenId CProtection tokenId
* @return amount locked
*/
function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){
address underlyingAsset = getUnderlyingAsset(tokenId);
uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset);
// calculates total protection value
uint256 protectionValue = div_(
mul_(
getUnderlyingAmount(tokenId),
getUnderlyingStrikePrice(tokenId)
),
assetDecimalsMantissa
);
// return value is lockedValue / totalValue * amount
return div_(
mul_(
getUnderlyingAmount(tokenId),
div_(
mul_(
_underlyingProtectionLockedValue[tokenId],
1e18
),
protectionValue
)
),
1e18
);
}
/**
* @notice Locks the given protection value as collateral optimization
* @param tokenId The MProtection token id
* @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization
* @return locked protection value
* TODO: convert semantic errors to standarized error codes
*/
function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) {
//check if the protection belongs to the caller
require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION");
address currency = getUnderlyingAsset(tokenId);
Moartroller moartroller = Moartroller(_moartrollerAddress);
MToken mToken = moartroller.tokenAddressToMToken(currency);
require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE");
uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId);
uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId));
// add protection locked value if any
uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId);
if ( protectionLockedValue > 0) {
maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue);
}
uint valueToLock;
if (value != 0) {
// check if lock value is at most max optimizable value
require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE");
// check if lock value is at most protection total value
require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE");
valueToLock = value;
} else {
// if we want to lock maximum protection value let's lock the value that is at most max optimizable value
if (protectionTotalValue > maxOptimizableValue) {
valueToLock = maxOptimizableValue;
} else {
valueToLock = protectionTotalValue;
}
}
_underlyingProtectionLockedValue[tokenId] = valueToLock;
emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock);
return valueToLock;
}
function _setCopMapping(address newMapping) public onlyOwner {
_copMappingAddress = newMapping;
}
function _setMoartroller(address newMoartroller) public onlyOwner {
_moartrollerAddress = newMoartroller;
}
function _setMaturityWindow(uint256 maturityWindow) public onlyOwner {
emit MaturityWindowUpdated(maturityWindow);
_maturityWindow = maturityWindow;
}
// MAPPINGS
function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getProtectionData(underlyingTokenId);
}
function getUnderlyingAsset(uint256 tokenId) public view returns (address){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAsset(underlyingTokenId);
}
function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingAmount(underlyingTokenId);
}
function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingStrikePrice(underlyingTokenId);
}
function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){
uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId);
return copMapping().getUnderlyingDeadline(underlyingTokenId);
}
function getContractVersion() external override pure returns(string memory){
return "V1";
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface PriceOracle {
/**
* @notice Get the underlying price of a mToken asset
* @param mToken The mToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(MToken mToken) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
abstract contract MTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @dev EIP-20 token name for this token
*/
string public name;
/**
* @dev EIP-20 token symbol for this token
*/
string public symbol;
/**
* @dev EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Underlying asset for this MToken
*/
address public underlying;
/**
* @dev Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal borrowRateMaxMantissa;
/**
* @dev Maximum fraction of interest that can be set aside for reserves
*/
uint internal reserveFactorMaxMantissa;
/**
* @dev Administrator for this contract
*/
address payable public admin;
/**
* @dev Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @dev Contract which oversees inter-mToken operations
*/
Moartroller public moartroller;
/**
* @dev Model which tells what the current interest rate should be
*/
AbstractInterestRateModel public interestRateModel;
/**
* @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @dev Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @dev Fraction of reserves currently set aside for other usage
*/
uint public reserveSplitFactorMantissa;
/**
* @dev Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @dev Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @dev Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @dev Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @dev Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000
*/
uint public maxProtectionComposition;
/**
* @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5
*/
uint public maxProtectionCompositionMantissa;
/**
* @dev Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @dev Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
struct ProtectionUsage {
uint256 protectionValueUsed;
}
/**
* @dev Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
mapping (uint256 => ProtectionUsage) protectionsUsed;
}
struct AccrueInterestTempStorage{
uint interestAccumulated;
uint reservesAdded;
uint splitedReserves_1;
uint splitedReserves_2;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
}
/**
* @dev Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) public accountBorrows;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./EIP20Interface.sol";
interface MTokenInterface {
/*** User contract ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function getCash() external view returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
function getUnderlying() external view returns(address);
function sweepToken(EIP20Interface token) external;
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface MProxyInterface {
function proxyClaimReward(address asset, address recipient, uint amount) external;
function proxySplitReserves(address asset, uint amount) external;
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./Interfaces/InterestRateModelInterface.sol";
abstract contract AbstractInterestRateModel is InterestRateModelInterface {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @title Careful Math
* @author MOAR
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
import "../Utils/ExponentialNoError.sol";
interface MoartrollerInterface {
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `mTokenBalance` is the number of mTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint mTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
ExponentialNoError.Exp collateralFactor;
ExponentialNoError.Exp exchangeRate;
ExponentialNoError.Exp oraclePrice;
ExponentialNoError.Exp tokensToDenom;
}
/*** Assets You Are In ***/
function enterMarkets(address[] calldata mTokens) external returns (uint[] memory);
function exitMarket(address mToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint);
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint);
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint);
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeUserTokens(
address mTokenBorrowed,
address mTokenCollateral,
uint repayAmount,
address account) external view returns (uint, uint);
function getUserLockedAmount(MToken asset, address account) external view returns(uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface Versionable {
function getContractVersion() external pure returns (string memory);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/PriceOracle.sol";
import "./Interfaces/LiquidityMathModelInterface.sol";
import "./Interfaces/LiquidationModelInterface.sol";
import "./MProtection.sol";
abstract contract UnitrollerAdminStorage {
/**
* @dev Administrator for this contract
*/
address public admin;
/**
* @dev Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @dev Active brains of Unitroller
*/
address public moartrollerImplementation;
/**
* @dev Pending brains of Unitroller
*/
address public pendingMoartrollerImplementation;
}
contract MoartrollerV1Storage is UnitrollerAdminStorage {
/**
* @dev Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @dev Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @dev Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @dev Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => MToken[]) public accountAssets;
}
contract MoartrollerV2Storage is MoartrollerV1Storage {
struct Market {
// Whether or not this market is listed
bool isListed;
// Multiplier representing the most one can borrow against their collateral in this market.
// For instance, 0.9 to allow borrowing 90% of collateral value.
// Must be between 0 and 1, and stored as a mantissa.
uint collateralFactorMantissa;
// Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
// Whether or not this market receives MOAR
bool isMoared;
}
/**
* @dev Official mapping of mTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @dev The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract MoartrollerV3Storage is MoartrollerV2Storage {
struct MoarMarketState {
// The market's last updated moarBorrowIndex or moarSupplyIndex
uint224 index;
// The block number the index was last updated at
uint32 block;
}
/// @dev A list of all markets
MToken[] public allMarkets;
/// @dev The rate at which the flywheel distributes MOAR, per block
uint public moarRate;
/// @dev The portion of moarRate that each market currently receives
mapping(address => uint) public moarSpeeds;
/// @dev The MOAR market supply state for each market
mapping(address => MoarMarketState) public moarSupplyState;
/// @dev The MOAR market borrow state for each market
mapping(address => MoarMarketState) public moarBorrowState;
/// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarSupplierIndex;
/// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR
mapping(address => mapping(address => uint)) public moarBorrowerIndex;
/// @dev The MOAR accrued but not yet transferred to each user
mapping(address => uint) public moarAccrued;
}
contract MoartrollerV4Storage is MoartrollerV3Storage {
// @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
}
contract MoartrollerV5Storage is MoartrollerV4Storage {
/// @dev The portion of MOAR that each contributor receives per block
mapping(address => uint) public moarContributorSpeeds;
/// @dev Last block at which a contributor's MOAR rewards have been allocated
mapping(address => uint) public lastContributorBlock;
}
contract MoartrollerV6Storage is MoartrollerV5Storage {
/**
* @dev Moar token address
*/
address public moarToken;
/**
* @dev MProxy address
*/
address public mProxy;
/**
* @dev CProtection contract which can be used for collateral optimisation
*/
MProtection public cprotection;
/**
* @dev Mapping for basic token address to mToken
*/
mapping(address => MToken) public tokenAddressToMToken;
/**
* @dev Math model for liquidity calculation
*/
LiquidityMathModelInterface public liquidityMathModel;
/**
* @dev Liquidation model for liquidation related functions
*/
LiquidationModelInterface public liquidationModel;
/**
* @dev List of addresses with privileged access
*/
mapping(address => uint) public privilegedAddresses;
/**
* @dev Determines if reward claim feature is enabled
*/
bool public rewardClaimEnabled;
}
// Copyright (c) 2020 The UNION Protocol Foundation
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// import "hardhat/console.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/**
* @title UNION Protocol Governance Token
* @dev Implementation of the basic standard token.
*/
contract UnionGovernanceToken is AccessControl, IERC20 {
using Address for address;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/**
* @notice Struct for marking number of votes from a given block
* @member from
* @member votes
*/
struct VotingCheckpoint {
uint256 from;
uint256 votes;
}
/**
* @notice Struct for locked tokens
* @member amount
* @member releaseTime
* @member votable
*/
struct LockedTokens{
uint amount;
uint releaseTime;
bool votable;
}
/**
* @notice Struct for EIP712 Domain
* @member name
* @member version
* @member chainId
* @member verifyingContract
* @member salt
*/
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
bytes32 salt;
}
/**
* @notice Struct for EIP712 VotingDelegate call
* @member owner
* @member delegate
* @member nonce
* @member expirationTime
*/
struct VotingDelegate {
address owner;
address delegate;
uint256 nonce;
uint256 expirationTime;
}
/**
* @notice Struct for EIP712 Permit call
* @member owner
* @member spender
* @member value
* @member nonce
* @member deadline
*/
struct Permit {
address owner;
address spender;
uint256 value;
uint256 nonce;
uint256 deadline;
}
/**
* @notice Vote Delegation Events
*/
event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate);
event VotingDelegateRemoved(address indexed _owner);
/**
* @notice Vote Balance Events
* Emmitted when a delegate account's vote balance changes at the time of a written checkpoint
*/
event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance);
/**
* @notice Transfer/Allocator Events
*/
event TransferStatusChanged(bool _newTransferStatus);
/**
* @notice Reversion Events
*/
event ReversionStatusChanged(bool _newReversionSetting);
/**
* @notice EIP-20 Approval event
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @notice EIP-20 Transfer event
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Burn(address indexed _from, uint256 _value);
event AddressPermitted(address indexed _account);
event AddressRestricted(address indexed _account);
/**
* @dev AccessControl recognized roles
*/
bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE");
bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN");
bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT");
bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK");
bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED");
bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST");
bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"
);
bytes32 public constant DELEGATE_TYPEHASH = keccak256(
"DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)"
);
//keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
address private constant BURN_ADDRESS = address(0);
address public UPGT_CONTRACT_ADDRESS;
/**
* @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting.
*/
bytes32 public immutable EIP712DOMAIN_SEPARATOR;
/**
* @dev EIP-20 token name
*/
string public name = "UNION Protocol Governance Token";
/**
* @dev EIP-20 token symbol
*/
string public symbol = "UNN";
/**
* @dev EIP-20 token decimals
*/
uint8 public decimals = 18;
/**
* @dev Contract version
*/
string public constant version = '0.0.1';
/**
* @dev Initial amount of tokens
*/
uint256 private uint256_initialSupply = 100000000000 * 10**18;
/**
* @dev Total amount of tokens
*/
uint256 private uint256_totalSupply;
/**
* @dev Chain id
*/
uint256 private uint256_chain_id;
/**
* @dev general transfer restricted as function of public sale not complete
*/
bool private b_canTransfer = false;
/**
* @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions.
*/
bool private b_revert = false; //false allows false return values
/**
* @dev Locked destinations list
*/
mapping(address => bool) private m_lockedDestinations;
/**
* @dev EIP-20 allowance and balance maps
*/
mapping(address => mapping(address => uint256)) private m_allowances;
mapping(address => uint256) private m_balances;
mapping(address => LockedTokens[]) private m_lockedBalances;
/**
* @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712
*/
mapping(address => uint256) private m_nonces;
/**
* @dev delegated account may for off-line vote delegation
*/
mapping(address => address) private m_delegatedAccounts;
/**
* @dev delegated account inverse map is needed to live calculate voting power
*/
mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap;
/**
* @dev indexed mapping of vote checkpoints for each account
*/
mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints;
/**
* @dev mapping of account addrresses to voting checkpoints
*/
mapping(address => uint256) private m_accountVotingCheckpoints;
/**
* @dev Contructor for the token
* @param _owner address of token contract owner
* @param _initialSupply of tokens generated by this contract
* Sets Transfer the total suppply to the owner.
* Sets default admin role to the owner.
* Sets ROLE_ALLOCATE to the owner.
* Sets ROLE_GOVERN to the owner.
* Sets ROLE_MINT to the owner.
* Sets EIP 712 Domain Separator.
*/
constructor(address _owner, uint256 _initialSupply) public {
//set internal contract references
UPGT_CONTRACT_ADDRESS = address(this);
//setup roles using AccessControl
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(ROLE_ADMIN, _owner);
_setupRole(ROLE_ADMIN, _msgSender());
_setupRole(ROLE_ALLOCATE, _owner);
_setupRole(ROLE_ALLOCATE, _msgSender());
_setupRole(ROLE_TRUSTED, _owner);
_setupRole(ROLE_TRUSTED, _msgSender());
_setupRole(ROLE_GOVERN, _owner);
_setupRole(ROLE_MINT, _owner);
_setupRole(ROLE_LOCK, _owner);
_setupRole(ROLE_TEST, _owner);
m_balances[_owner] = _initialSupply;
uint256_totalSupply = _initialSupply;
b_canTransfer = false;
uint256_chain_id = _getChainId();
EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({
name : name,
version : version,
chainId : uint256_chain_id,
verifyingContract : address(this),
salt : keccak256(abi.encodePacked(name))
}
));
emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply);
}
/**
* @dev Sets transfer status to lock token transfer
* @param _canTransfer value can be true or false.
* disables transfer when set to false and enables transfer when true
* Only a member of ADMIN role can call to change transfer status
*/
function setCanTransfer(bool _canTransfer) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
b_canTransfer = _canTransfer;
emit TransferStatusChanged(_canTransfer);
}
}
/**
* @dev Gets status of token transfer lock
* @return true or false status of whether the token can be transfered
*/
function getCanTransfer() public view returns (bool) {
return b_canTransfer;
}
/**
* @dev Sets transfer reversion status to either return false or throw on error
* @param _reversion value can be true or false.
* disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true
* Only a member of ADMIN role can call to change transfer reversion status
*/
function setReversion(bool _reversion) public {
if(hasRole(ROLE_ADMIN, _msgSender()) ||
hasRole(ROLE_TEST, _msgSender())
) {
b_revert = _reversion;
emit ReversionStatusChanged(_reversion);
}
}
/**
* @dev Gets status of token transfer reversion
* @return true or false status of whether the token transfer failures return false or are reverted
*/
function getReversion() public view returns (bool) {
return b_revert;
}
/**
* @dev retrieve current chain id
* @return chain id
*/
function getChainId() public pure returns (uint256) {
return _getChainId();
}
/**
* @dev Retrieve current chain id
* @return chain id
*/
function _getChainId() internal pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* @dev Retrieve total supply of tokens
* @return uint256 total supply of tokens
*/
function totalSupply() public view override returns (uint256) {
return uint256_totalSupply;
}
/**
* Balance related functions
*/
/**
* @dev Retrieve balance of a specified account
* @param _account address of account holding balance
* @return uint256 balance of the specified account address
*/
function balanceOf(address _account) public view override returns (uint256) {
return m_balances[_account].add(_calculateReleasedBalance(_account));
}
/**
* @dev Retrieve locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function lockedBalanceOf(address _account) public view returns (uint256) {
return _calculateLockedBalance(_account);
}
/**
* @dev Retrieve lenght of locked balance array for specific address
* @param _account address of account holding locked balance
* @return uint256 locked balance array lenght
*/
function getLockedTokensListSize(address _account) public view returns (uint256){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
return m_lockedBalances[_account].length;
}
/**
* @dev Retrieve locked tokens struct from locked balance array for specific address
* @param _account address of account holding locked tokens
* @param _index index in array with locked tokens position
* @return amount of locked tokens
* @return releaseTime descibes time when tokens will be unlocked
* @return votable flag is describing votability of tokens
*/
function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){
require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions");
require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index");
LockedTokens storage lockedTokens = m_lockedBalances[_account][_index];
return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable);
}
/**
* @dev Calculates locked balance of a specified account
* @param _account address of account holding locked balance
* @return uint256 locked balance of the specified account address
*/
function _calculateLockedBalance(address _account) private view returns (uint256) {
uint256 lockedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime > block.timestamp){
lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedBalance;
}
/**
* @dev Calculates released balance of a specified account
* @param _account address of account holding released balance
* @return uint256 released balance of the specified account address
*/
function _calculateReleasedBalance(address _account) private view returns (uint256) {
uint256 releasedBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount);
}
}
return releasedBalance;
}
/**
* @dev Calculates locked votable balance of a specified account
* @param _account address of account holding locked votable balance
* @return uint256 locked votable balance of the specified account address
*/
function _calculateLockedVotableBalance(address _account) private view returns (uint256) {
uint256 lockedVotableBalance = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].votable == true){
lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount);
}
}
return lockedVotableBalance;
}
/**
* @dev Moves released balance to normal balance for a specified account
* @param _account address of account holding released balance
*/
function _moveReleasedBalance(address _account) internal virtual{
uint256 releasedToMove = 0;
for (uint i=0; i<m_lockedBalances[_account].length; i++) {
if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){
releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount);
m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1];
m_lockedBalances[_account].pop();
}
}
m_balances[_account] = m_balances[_account].add(releasedToMove);
}
/**
* Allowance related functinons
*/
/**
* @dev Retrieve the spending allowance for a token holder by a specified account
* @param _owner Token account holder
* @param _spender Account given allowance
* @return uint256 allowance value
*/
function allowance(address _owner, address _spender) public override virtual view returns (uint256) {
return m_allowances[_owner][_spender];
}
/**
* @dev Message sender approval to spend for a specified amount
* @param _spender address of party approved to spend
* @param _value amount of the approval
* @return boolean success status
* public wrapper for _approve, _owner is msg.sender
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
bool success = _approveUNN(_msgSender(), _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: APPROVE ERROR");
}
return success;
}
/**
* @dev Token owner approval of amount for specified spender
* @param _owner address of party that owns the tokens being granted approval for spending
* @param _spender address of party that is granted approval for spending
* @param _value amount approved for spending
* @return boolean approval status
* if _spender allownace for a given _owner is greater than 0,
* increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738
*/
function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(m_allowances[_owner][_spender] == 0 || _value == 0)
){
m_allowances[_owner][_spender] = _value;
emit Approval(_owner, _spender, _value);
retval = true;
}
return retval;
}
/**
* @dev Increase spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _addedValue specified incremental increase
* @return boolean increaseAllowance status
* public wrapper for _increaseAllowance, _owner restricted to msg.sender
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue);
if(!success && b_revert){
revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to increase spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _addedValue specified incremental increase
* @return boolean return value status
* increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address.
*/
function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_addedValue > 0
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* @dev Decrease spender allowance by specified incremental value
* @param _spender address of party that is granted approval for spending
* @param _subtractedValue specified incremental decrease
* @return boolean success status
* public wrapper for _decreaseAllowance, _owner restricted to msg.sender
*/
//public wrapper for _decreaseAllowance, _owner restricted to msg.sender
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue);
if(!success && b_revert){
revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR");
}
return success;
}
/**
* @dev Allow owner to decrease spender allowance by specified incremental value
* @param _owner address of the token owner
* @param _spender address of the token spender
* @param _subtractedValue specified incremental decrease
* @return boolean return value status
* decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address.
*/
function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) {
bool retval = false;
if(_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
_subtractedValue > 0 &&
m_allowances[_owner][_spender] >= _subtractedValue
){
m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue);
retval = true;
emit Approval(_owner, _spender, m_allowances[_owner][_spender]);
}
return retval;
}
/**
* LockedDestination related functions
*/
/**
* @dev Adds address as a designated destination for tokens when locked for allocation only
* @param _address Address of approved desitnation for movement during lock
* @return success in setting address as eligible for transfer independent of token lock status
*/
function setAsEligibleLockedDestination(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
m_lockedDestinations[_address] = true;
retVal = true;
}
return retVal;
}
/**
* @dev removes desitnation as eligible for transfer
* @param _address address being removed
*/
function removeEligibleLockedDestination(address _address) public {
if(hasRole(ROLE_ADMIN, _msgSender())){
require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
delete(m_lockedDestinations[_address]);
}
}
/**
* @dev checks whether a destination is eligible as recipient of transfer independent of token lock status
* @param _address address being checked
* @return whether desitnation is locked
*/
function checkEligibleLockedDesination(address _address) public view returns (bool) {
return m_lockedDestinations[_address];
}
/**
* @dev Adds address as a designated allocator that can move tokens when they are locked
* @param _address Address receiving the role of ROLE_ALLOCATE
* @return success as true or false
*/
function setAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
grantRole(ROLE_ALLOCATE, _address);
retVal = true;
}
return retVal;
}
/**
* @dev Removes address as a designated allocator that can move tokens when they are locked
* @param _address Address being removed from the ROLE_ALLOCATE
* @return success as true or false
*/
function removeAsAllocator(address _address) public returns (bool) {
bool retVal = false;
if(hasRole(ROLE_ADMIN, _msgSender())){
if(hasRole(ROLE_ALLOCATE, _address)){
revokeRole(ROLE_ALLOCATE, _address);
retVal = true;
}
}
return retVal;
}
/**
* @dev Checks to see if an address has the role of being an allocator
* @param _address Address being checked for ROLE_ALLOCATE
* @return true or false whether the address has ROLE_ALLOCATE assigned
*/
function checkAsAllocator(address _address) public view returns (bool) {
return hasRole(ROLE_ALLOCATE, _address);
}
/**
* Transfer related functions
*/
/**
* @dev Public wrapper for transfer function to move tokens of specified value to a given address
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @return status of transfer success
*/
function transfer(address _to, uint256 _value) external override returns (bool) {
bool success = _transferUNN(_msgSender(), _to, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER");
}
return success;
}
/**
* @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required.
* @param _owner The address owner where transfer originates
* @param _to The address to transfer to
* @param _value The amount to be transferred
* @return status of transfer success
*/
function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_to] = m_balances[_to].add(_value);
retval = true;
//need to move voting delegates with transfer of tokens
retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value to a given address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value >= 0)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
retval = true;
//need to move voting delegates with transfer of tokens
// retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFrom function
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) {
bool success = _transferFromUNN(_owner, _spender, _value);
if(!success && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM");
}
return success;
}
/**
* @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn
* @param _owner The address to transfer from
* @param _spender cannot be the burn address
* @param _value The amount to be transferred
* @return status of transferFrom success
* _spender cannot be either this goverance token contract or burn
*/
function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) {
if(
_spender != BURN_ADDRESS &&
_spender != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_balances[_spender] = m_balances[_spender].add(_value);
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
retval = retval && _moveVotingDelegates(_owner, _spender, _value);
emit Transfer(_owner, _spender, _value);
}
}
return retval;
}
/**
* @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
* Requires ROLE_LOCK
*/
function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) {
bool retval = false;
if(hasRole(ROLE_LOCK, _msgSender())){
retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable);
}
if(!retval && b_revert){
revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK");
}
return retval;
}
/**
* @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time
* @param _owner The address owner where transfer originates
* @param _to specified recipient
* @param _value amount being transfered to recipient
* @param _releaseTime time in seconds after amount will be released
* @param _votable flag which describes if locked tokens are votable or not
* @return status of transfer success
*/
function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) {
bool retval = false;
if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) {
if(
_to != BURN_ADDRESS &&
_to != UPGT_CONTRACT_ADDRESS &&
(balanceOf(_owner) >= _value) &&
(_value > 0) &&
(m_allowances[_owner][_msgSender()] >= _value)
){
_moveReleasedBalance(_owner);
m_balances[_owner] = m_balances[_owner].sub(_value);
m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable));
m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value);
retval = true;
//need to move delegates that exist for this owner in line with transfer
// retval = retval && _moveVotingDelegates(_owner, _to, _value);
emit Transfer(_owner, _to, _value);
}
}
return retval;
}
/**
* @dev Public function to burn tokens
* @param _value number of tokens to be burned
* @return whether tokens were burned
* Only ROLE_MINTER may burn tokens
*/
function burn(uint256 _value) external returns (bool) {
bool success = _burn(_value);
if(!success && b_revert){
revert("UPGT_ERROR: FAILED TO BURN");
}
return success;
}
/**
* @dev Private function Burn tokens
* @param _value number of tokens to be burned
* @return bool whether the tokens were burned
* only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet.
*/
function _burn(uint256 _value) internal returns (bool) {
bool retval = false;
if(hasRole(ROLE_MINT, _msgSender()) &&
(m_balances[_msgSender()] >= _value)
){
m_balances[_msgSender()] -= _value;
uint256_totalSupply = uint256_totalSupply.sub(_value);
retval = true;
emit Burn(_msgSender(), _value);
}
return retval;
}
/**
* Voting related functions
*/
/**
* @dev Public wrapper for _calculateVotingPower function which calulates voting power
* @dev voting power = balance + locked votable balance + delegations
* @return uint256 voting power
*/
function calculateVotingPower() public view returns (uint256) {
return _calculateVotingPower(_msgSender());
}
/**
* @dev Calulates voting power of specified address
* @param _account address of token holder
* @return uint256 voting power
*/
function _calculateVotingPower(address _account) private view returns (uint256) {
uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account));
for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) {
if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){
address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i);
votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount));
}
}
return votingPower;
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
* Requires ROLE_TEST
*/
function moveVotingDelegates(
address _source,
address _destination,
uint256 _amount) public returns (bool) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _moveVotingDelegates(_source, _destination, _amount);
}
/**
* @dev Moves a number of votes from a token holder to a designated representative
* @param _source address of token holder
* @param _destination address of voting delegate
* @param _amount of voting delegation transfered to designated representative
* @return bool whether move was successful
*/
function _moveVotingDelegates(
address _source,
address _destination,
uint256 _amount
) internal returns (bool) {
if(_source != _destination && _amount > 0) {
if(_source != BURN_ADDRESS) {
uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source];
uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0;
if(sourceNumberOfVotingCheckpointsOriginal >= _amount) {
uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount);
_writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew);
}
}
if(_destination != BURN_ADDRESS) {
uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination];
uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0;
uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount);
_writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew);
}
}
return true;
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Public function for writing voting checkpoint
* Requires ROLE_TEST
*/
function writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) public {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
_writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes);
}
/**
* @dev Writes voting checkpoint for a given voting delegate
* @param _votingDelegate exercising votes
* @param _numberOfVotingCheckpoints number of voting checkpoints for current vote
* @param _oldVotes previous number of votes
* @param _newVotes new number of votes
* Private function for writing voting checkpoint
*/
function _writeVotingCheckpoint(
address _votingDelegate,
uint256 _numberOfVotingCheckpoints,
uint256 _oldVotes,
uint256 _newVotes) internal {
if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes;
}
else {
m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes);
_numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1);
}
emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes);
}
/**
* @dev Calculate account votes as of a specific block
* @param _account address whose votes are counted
* @param _blockNumber from which votes are being counted
* @return number of votes counted
*/
function getVoteCountAtBlock(
address _account,
uint256 _blockNumber) public view returns (uint256) {
uint256 voteCount = 0;
if(_blockNumber < block.number) {
if(m_accountVotingCheckpoints[_account] != 0) {
if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) {
voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes;
}
else if(m_votingCheckpoints[_account][0].from > _blockNumber) {
voteCount = 0;
}
else {
uint256 lower = 0;
uint256 upper = m_accountVotingCheckpoints[_account].sub(1);
while(upper > lower) {
uint256 center = upper.sub((upper.sub(lower).div(2)));
VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center];
if(votingCheckpoint.from == _blockNumber) {
voteCount = votingCheckpoint.votes;
break;
}
else if(votingCheckpoint.from < _blockNumber) {
lower = center;
}
else {
upper = center.sub(1);
}
}
}
}
}
return voteCount;
}
/**
* @dev Vote Delegation Functions
* @param _to address where message sender is assigning votes
* @return success of message sender delegating vote
* delegate function does not allow assignment to burn
*/
function delegateVote(address _to) public returns (bool) {
return _delegateVote(_msgSender(), _to);
}
/**
* @dev Delegate votes from token holder to another address
* @param _from Token holder
* @param _toDelegate Address that will be delegated to for purpose of voting
* @return success as to whether delegation has been a success
*/
function _delegateVote(
address _from,
address _toDelegate) internal returns (bool) {
bool retval = false;
if(_toDelegate != BURN_ADDRESS) {
address currentDelegate = m_delegatedAccounts[_from];
uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from));
address oldToDelegate = m_delegatedAccounts[_from];
m_delegatedAccounts[_from] = _toDelegate;
m_delegatedAccountsInverseMap[oldToDelegate].remove(_from);
if(_from != _toDelegate){
m_delegatedAccountsInverseMap[_toDelegate].add(_from);
}
retval = true;
retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance);
if(retval) {
if(_from == _toDelegate){
emit VotingDelegateRemoved(_from);
}
else{
emit VotingDelegateChanged(_from, currentDelegate, _toDelegate);
}
}
}
return retval;
}
/**
* @dev Revert voting delegate control to owner account
* @param _account The account that has delegated its vote
* @return success of reverting delegation to owner
*/
function _revertVotingDelegationToOwner(address _account) internal returns (bool) {
return _delegateVote(_account, _account);
}
/**
* @dev Used by an message sending account to recall its voting delegates
* @return success of reverting delegation to owner
*/
function recallVotingDelegate() public returns (bool) {
return _revertVotingDelegationToOwner(_msgSender());
}
/**
* @dev Retrieve the voting delegate for a specified account
* @param _account The account that has delegated its vote
*/
function getVotingDelegate(address _account) public view returns (address) {
return m_delegatedAccounts[_account];
}
/**
* EIP-712 related functions
*/
/**
* @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit
* @param _owner address of token owner
* @param _spender address of designated spender
* @param _value value permitted for spend
* @param _deadline expiration of signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline))
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _approveUNN(_owner, _spender, _value);
}
/**
* @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote
* @param _owner address of token owner
* @param _delegate address of voting delegate
* @param _expiretimestamp expiration of delegation signature
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @ @return bool true or false depedening on whether vote was successfully delegated
*/
function delegateVoteBySignature(
address _owner,
address _delegate,
uint256 _expiretimestamp,
uint8 _ecv,
bytes32 _ecr,
bytes32 _ecs
) external returns (bool) {
require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp");
require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
EIP712DOMAIN_SEPARATOR,
_hash(VotingDelegate(
{
owner : _owner,
delegate : _delegate,
nonce : m_nonces[_owner]++,
expirationTime : _expiretimestamp
})
)
)
);
require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user");
require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address");
return _delegateVote(_owner, _delegate);
}
/**
* @dev Public hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
* Requires ROLE_TEST
*/
function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_eip712Domain);
}
/**
* @dev Hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
* Requires ROLE_TEST
*/
function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_delegate);
}
/**
* @dev Public hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
* Requires ROLE_TEST
*/
function hashPermit(Permit memory _permit) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_permit);
}
/**
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
* Requires ROLE_TEST
*/
function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _recoverSigner(_digest, _ecv, _ecr, _ecs);
}
/**
* @dev Private hash EIP712Domain struct for EIP-712
* @param _eip712Domain EIP712Domain struct
* @return bytes32 hash of _eip712Domain
*/
function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) {
return keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(_eip712Domain.name)),
keccak256(bytes(_eip712Domain.version)),
_eip712Domain.chainId,
_eip712Domain.verifyingContract,
_eip712Domain.salt
)
);
}
/**
* @dev Private hash Delegate struct for EIP-712
* @param _delegate VotingDelegate struct
* @return bytes32 hash of _delegate
*/
function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) {
return keccak256(
abi.encode(
DELEGATE_TYPEHASH,
_delegate.owner,
_delegate.delegate,
_delegate.nonce,
_delegate.expirationTime
)
);
}
/**
* @dev Private hash Permit struct for EIP-712
* @param _permit Permit struct
* @return bytes32 hash of _permit
*/
function _hash(Permit memory _permit) internal pure returns (bytes32) {
return keccak256(abi.encode(
PERMIT_TYPEHASH,
_permit.owner,
_permit.spender,
_permit.value,
_permit.nonce,
_permit.deadline
));
}
/**
* @dev Recover signer information from provided digest
* @param _digest signed, hashed message
* @param _ecv ECDSA v parameter
* @param _ecr ECDSA r parameter
* @param _ecs ECDSA s parameter
* @return address of the validated signer
* based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function
*/
function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) 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.
if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if(_ecv != 27 && _ecv != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(_digest, _ecv, _ecr, _ecs);
require(signer != BURN_ADDRESS, "ECDSA: invalid signature");
return signer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../Interfaces/EIP20Interface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title SafeEIP20
* @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.
* This is a forked version of Openzeppelin's SafeERC20 contract but supporting
* EIP20Interface instead of Openzeppelin's IERC20
* 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 SafeEIP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(EIP20Interface token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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 experimental ABIEncoderV2;
import "./PriceOracle.sol";
import "./MoartrollerInterface.sol";
pragma solidity ^0.6.12;
interface LiquidationModelInterface {
function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint);
struct LiquidateCalculateSeizeUserTokensArgumentsSet {
PriceOracle oracle;
MoartrollerInterface moartroller;
address mTokenBorrowed;
address mTokenCollateral;
uint actualRepayAmount;
address accountForLiquidation;
uint liquidationIncentiveMantissa;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
/**
* @title MOAR's InterestRateModel Interface
* @author MOAR
*/
interface InterestRateModelInterface {
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/EnumerableSetUpgradeable.sol";
import "../../utils/EnumerableMapUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.UintToAddressMap 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.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721Upgradeable.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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.12;
interface CopMappingInterface {
function getTokenAddress() external view returns (address);
function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint);
function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address);
function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256);
function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint);
function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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.6.2 <0.8.0;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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 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.6.0 <0.8.0;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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 EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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 EnumerableMapUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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 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.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @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 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: BSD-3-Clause
pragma solidity ^0.6.12;
import "./MToken.sol";
import "./Interfaces/MErc20Interface.sol";
import "./Moartroller.sol";
import "./AbstractInterestRateModel.sol";
import "./Interfaces/EIP20Interface.sol";
import "./Utils/SafeEIP20.sol";
/**
* @title MOAR's MErc20 Contract
* @notice MTokens which wrap an EIP-20 underlying
*/
contract MErc20 is MToken, MErc20Interface {
using SafeEIP20 for EIP20Interface;
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param moartroller_ The address of the Moartroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function init(address underlying_,
Moartroller moartroller_,
AbstractInterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// MToken initialize does the bulk of the work
super.init(moartroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives mTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external override returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems mTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of mTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external override returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems mTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external override returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external override returns (uint) {
return borrowInternal(borrowAmount);
}
function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) {
return borrowForInternal(borrower, borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external override returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower.
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this mToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param mTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external override returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral);
return err;
}
/**
* @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock)
* @param token The address of the ERC-20 token to sweep
*/
function sweepToken(EIP20Interface token) override external {
require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token");
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(admin, balance);
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external override returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal override view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*`
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal override returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
uint balanceBefore = token.balanceOf(address(this));
token.safeTransferFrom(from, address(this), amount);
// Calculate the amount that was *actually* transferred
uint balanceAfter = token.balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal override {
EIP20Interface token = EIP20Interface(underlying);
token.safeTransfer(to, amount);
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
import "../MToken.sol";
interface MErc20Interface {
/*** User contract ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function borrowFor(address payable borrower, uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
|
Public hash EIP712Domain struct for EIP-712 _eip712Domain EIP712Domain struct return bytes32 hash of _eip712Domain Requires ROLE_TEST/
|
function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) {
require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required");
return _hash(_eip712Domain);
}
| 11,818,613
|
./full_match/1/0x2BB3a198bE77Ef9b14e3Fa1d58F2743328982b59/sources/1.sol
|
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() internal virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
address payable internal dev = payable(0xA0D0de1070948cF0CBD6Bdf4fB34D4D056bE7bC5);
| 2,929,536
|
pragma solidity ^0.5.16;
// Inheritance
import "./PerpsV2MarketBase.sol";
/**
Mixin that implements NextPrice orders mechanism for the perps market.
The purpose of the mechanism is to allow reduced fees for trades that commit to next price instead
of current price. Specifically, this should serve funding rate arbitrageurs, such that funding rate
arb is profitable for smaller skews. This in turn serves the protocol by reducing the skew, and so
the risk to the debt pool, and funding rate for traders.
The fees can be reduced when comitting to next price, because front-running (MEV and oracle delay)
is less of a risk when committing to next price.
The relative complexity of the mechanism is due to having to enforce the "commitment" to the trade
without either introducing free (or cheap) optionality to cause cancellations, and without large
sacrifices to the UX / risk of the traders (e.g. blocking all actions, or penalizing failures too much).
*/
contract PerpsV2NextPriceMixin is PerpsV2MarketBase {
/// @dev Holds a mapping of accounts to orders. Only one order per account is supported
mapping(address => NextPriceOrder) public nextPriceOrders;
///// Mutative methods
/**
* @notice submits an order to be filled at a price of the next oracle update.
* Reverts if a previous order still exists (wasn't executed or cancelled).
* Reverts if the order cannot be filled at current price to prevent witholding commitFee for
* incorrectly submitted orders (that cannot be filled).
* @param sizeDelta size in baseAsset (notional terms) of the order, similar to `modifyPosition` interface
*/
function submitNextPriceOrder(int sizeDelta) external {
_submitNextPriceOrder(sizeDelta, bytes32(0));
}
/// same as submitNextPriceOrder but emits an event with the tracking code
/// to allow volume source fee sharing for integrations
function submitNextPriceOrderWithTracking(int sizeDelta, bytes32 trackingCode) external {
_submitNextPriceOrder(sizeDelta, trackingCode);
}
function _submitNextPriceOrder(int sizeDelta, bytes32 trackingCode) internal {
// check that a previous order doesn't exist
require(nextPriceOrders[msg.sender].sizeDelta == 0, "previous order exists");
// storage position as it's going to be modified to deduct commitFee and keeperFee
Position storage position = positions[msg.sender];
// to prevent submitting bad orders in good faith and being charged commitDeposit for them
// simulate the order with current price and market and check that the order doesn't revert
uint price = _assetPriceRequireSystemChecks();
uint fundingIndex = _recomputeFunding(price);
TradeParams memory params =
TradeParams({
sizeDelta: sizeDelta,
price: price,
baseFee: _baseFeeNextPrice(marketKey),
trackingCode: trackingCode
});
(, , Status status) = _postTradeDetails(position, params);
_revertIfError(status);
// deduct fees from margin
uint commitDeposit = _nextPriceCommitDeposit(params);
uint keeperDeposit = _minKeeperFee();
_updatePositionMargin(position, price, -int(commitDeposit + keeperDeposit));
// emit event for modifying the position (subtracting the fees from margin)
emit PositionModified(position.id, msg.sender, position.margin, position.size, 0, price, fundingIndex, 0);
// create order
uint targetRoundId = _exchangeRates().getCurrentRoundId(baseAsset) + 1; // next round
NextPriceOrder memory order =
NextPriceOrder({
sizeDelta: int128(sizeDelta),
targetRoundId: uint128(targetRoundId),
commitDeposit: uint128(commitDeposit),
keeperDeposit: uint128(keeperDeposit),
trackingCode: trackingCode
});
// emit event
emit NextPriceOrderSubmitted(
msg.sender,
order.sizeDelta,
order.targetRoundId,
order.commitDeposit,
order.keeperDeposit,
order.trackingCode
);
// store order
nextPriceOrders[msg.sender] = order;
}
/**
* @notice Cancels an existing order for an account.
* Anyone can call this method for any account, but only the account owner
* can cancel their own order during the period when it can still potentially be executed (before it becomes stale).
* Only after the order becomes stale, can anyone else (e.g. a keeper) cancel the order for the keeperFee.
* Cancelling the order:
* - Removes the stored order.
* - commitFee (deducted during submission) is sent to the fee pool.
* - keeperFee (deducted during submission) is refunded into margin if it's the account holder,
* or send to the msg.sender if it's not the account holder.
* @param account the account for which the stored order should be cancelled
*/
function cancelNextPriceOrder(address account) external {
// important!! order of the account, not the msg.sender
NextPriceOrder memory order = nextPriceOrders[account];
// check that a previous order exists
require(order.sizeDelta != 0, "no previous order");
uint currentRoundId = _exchangeRates().getCurrentRoundId(baseAsset);
if (account == msg.sender) {
// this is account owner
// refund keeper fee to margin
Position storage position = positions[account];
uint price = _assetPriceRequireSystemChecks();
uint fundingIndex = _recomputeFunding(price);
_updatePositionMargin(position, price, int(order.keeperDeposit));
// emit event for modifying the position (add the fee to margin)
emit PositionModified(position.id, account, position.margin, position.size, 0, price, fundingIndex, 0);
} else {
// this is someone else (like a keeper)
// cancellation by third party is only possible when execution cannot be attempted any longer
// otherwise someone might try to grief an account by cancelling for the keeper fee
require(_confirmationWindowOver(currentRoundId, order.targetRoundId), "cannot be cancelled by keeper yet");
// send keeper fee to keeper
_manager().issueSUSD(msg.sender, order.keeperDeposit);
}
// pay the commitDeposit as fee to the FeePool
_manager().payFee(order.commitDeposit, order.trackingCode);
// remove stored order
// important!! position of the account, not the msg.sender
delete nextPriceOrders[account];
// emit event
emit NextPriceOrderRemoved(
account,
currentRoundId,
order.sizeDelta,
order.targetRoundId,
order.commitDeposit,
order.keeperDeposit,
order.trackingCode
);
}
/**
* @notice Tries to execute a previously submitted next-price order.
* Reverts if:
* - There is no order
* - Target roundId wasn't reached yet
* - Order is stale (target roundId is too low compared to current roundId).
* - Order fails for accounting reason (e.g. margin was removed, leverage exceeded, etc)
* If order reverts, it has to be removed by calling cancelNextPriceOrder().
* Anyone can call this method for any account.
* If this is called by the account holder - the keeperFee is refunded into margin,
* otherwise it sent to the msg.sender.
* @param account address of the account for which to try to execute a next-price order
*/
function executeNextPriceOrder(address account) external {
// important!: order of the account, not the sender!
NextPriceOrder memory order = nextPriceOrders[account];
// check that a previous order exists
require(order.sizeDelta != 0, "no previous order");
// check round-Id
uint currentRoundId = _exchangeRates().getCurrentRoundId(baseAsset);
require(order.targetRoundId <= currentRoundId, "target roundId not reached");
// check order is not too old to execute
// we cannot allow executing old orders because otherwise perps knowledge
// can be used to trigger failures of orders that are more profitable
// then the commitFee that was charged, or can be used to confirm
// orders that are more profitable than known then (which makes this into a "cheap option").
require(!_confirmationWindowOver(currentRoundId, order.targetRoundId), "order too old, use cancel");
// handle the fees and refunds according to the mechanism rules
uint toRefund = order.commitDeposit; // refund the commitment deposit
// refund keeperFee to margin if it's the account holder
if (msg.sender == account) {
toRefund += order.keeperDeposit;
} else {
_manager().issueSUSD(msg.sender, order.keeperDeposit);
}
Position storage position = positions[account];
uint currentPrice = _assetPriceRequireSystemChecks();
uint fundingIndex = _recomputeFunding(currentPrice);
// refund the commitFee (and possibly the keeperFee) to the margin before executing the order
// if the order later fails this is reverted of course
_updatePositionMargin(position, currentPrice, int(toRefund));
// emit event for modifying the position (refunding fee/s)
emit PositionModified(position.id, account, position.margin, position.size, 0, currentPrice, fundingIndex, 0);
// the correct price for the past round
(uint pastPrice, ) = _exchangeRates().rateAndTimestampAtRound(baseAsset, order.targetRoundId);
// execute or revert
_trade(
account,
TradeParams({
sizeDelta: order.sizeDelta, // using the pastPrice from the target roundId
price: pastPrice, // the funding is applied only from order confirmation time
baseFee: _baseFeeNextPrice(marketKey),
trackingCode: order.trackingCode
})
);
// remove stored order
delete nextPriceOrders[account];
// emit event
emit NextPriceOrderRemoved(
account,
currentRoundId,
order.sizeDelta,
order.targetRoundId,
order.commitDeposit,
order.keeperDeposit,
order.trackingCode
);
}
///// Internal views
// confirmation window is over when current roundId is more than nextPriceConfirmWindow
// rounds after target roundId
function _confirmationWindowOver(uint currentRoundId, uint targetRoundId) internal view returns (bool) {
return (currentRoundId > targetRoundId) && (currentRoundId - targetRoundId > _nextPriceConfirmWindow(marketKey)); // don't underflow
}
// convenience view to access exchangeRates contract for methods that are not exposed
// via _exchangeCircuitBreaker() contract
function _exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(_exchangeCircuitBreaker().exchangeRates());
}
// calculate the commitFee, which is the fee that would be charged on the order if it was spot
function _nextPriceCommitDeposit(TradeParams memory params) internal view returns (uint) {
// modify params to spot fee
params.baseFee = _baseFee(marketKey);
// Commit fee is equal to the spot fee that would be paid.
// This is to prevent free cancellation manipulations (by e.g. withdrawing the margin).
// The dynamic fee rate is passed as 0 since for the purposes of the commitment deposit
// it is not important since at the time of order execution it will be refunded and the correct
// dynamic fee will be charged.
return _orderFee(params, 0);
}
///// Events
event NextPriceOrderSubmitted(
address indexed account,
int sizeDelta,
uint targetRoundId,
uint commitDeposit,
uint keeperDeposit,
bytes32 trackingCode
);
event NextPriceOrderRemoved(
address indexed account,
uint currentRoundId,
int sizeDelta,
uint targetRoundId,
uint commitDeposit,
uint keeperDeposit,
bytes32 trackingCode
);
}
|
Tries to execute a previously submitted next-price order. Reverts if: - There is no order - Target roundId wasn't reached yet - Order is stale (target roundId is too low compared to current roundId). - Order fails for accounting reason (e.g. margin was removed, leverage exceeded, etc) If order reverts, it has to be removed by calling cancelNextPriceOrder(). Anyone can call this method for any account. If this is called by the account holder - the keeperFee is refunded into margin, otherwise it sent to the msg.sender. account address of the account for which to try to execute a next-price order/ important!: order of the account, not the sender! check that a previous order exists check round-Id check order is not too old to execute we cannot allow executing old orders because otherwise perps knowledge can be used to trigger failures of orders that are more profitable then the commitFee that was charged, or can be used to confirm orders that are more profitable than known then (which makes this into a "cheap option"). handle the fees and refunds according to the mechanism rules refund keeperFee to margin if it's the account holder
|
function executeNextPriceOrder(address account) external {
NextPriceOrder memory order = nextPriceOrders[account];
require(order.sizeDelta != 0, "no previous order");
uint currentRoundId = _exchangeRates().getCurrentRoundId(baseAsset);
require(order.targetRoundId <= currentRoundId, "target roundId not reached");
require(!_confirmationWindowOver(currentRoundId, order.targetRoundId), "order too old, use cancel");
if (msg.sender == account) {
toRefund += order.keeperDeposit;
_manager().issueSUSD(msg.sender, order.keeperDeposit);
}
Position storage position = positions[account];
uint currentPrice = _assetPriceRequireSystemChecks();
uint fundingIndex = _recomputeFunding(currentPrice);
account,
TradeParams({
baseFee: _baseFeeNextPrice(marketKey),
trackingCode: order.trackingCode
})
);
account,
currentRoundId,
order.sizeDelta,
order.targetRoundId,
order.commitDeposit,
order.keeperDeposit,
order.trackingCode
);
}
| 967,623
|
pragma solidity ^0.4.24;
contract LivenetErcCryptoKitties {
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CryptoKitties";
string public constant symbol = "CK";
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return true;
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Kitty.
/// @param _claimant the address we are validating against.
/// @param _tokenId kitten id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return true;
}
/// @dev Checks if a given address currently has transferApproval for a particular Kitty.
/// @param _claimant the address we are confirming kitten is approved for.
/// @param _tokenId kitten id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return true;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Kitties on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
}
/// @notice Returns the number of Kitties owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return 1;
}
/// @notice Transfers a Kitty to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoKitties specifically) or your Kitty may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Kitty to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
{
// for debug
emit Transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Kitty via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
{
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Kitty owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Kitty to be transfered.
/// @param _to The address that should take ownership of the Kitty. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Kitty to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
emit Transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of Kitties currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return 1;
}
/// @notice Returns the address currently assigned ownership of a given Kitty.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
return address(0);
}
}
|
Returns the address currently assigned ownership of a given Kitty. Required for ERC-721 compliance.
|
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
return address(0);
}
| 15,805,964
|
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.10;
pragma abicoder v2;
import "./interfaces/ITreasury.sol";
import "./interfaces/IStaking.sol";
import "./interfaces/IBondDepository.sol";
import "./types/Ownable.sol";
/**
* This contract allows Starship seed investors and advisors to claim tokens.
* step was taken to ensure fair distribution of exposure in the network.
*/
contract StarshipCrowdsale is Ownable {
/* ========== DEPENDENCIES ========== */
/* ========== EVENTS ========== */
event StarMinted(address caller, uint256 amount, address reserve);
event CrowdsaleInitialized(address caller, uint256 startTime);
/* ========== STATE VARIABLES ========== */
// our token
IERC20 public immutable star;
// receieves deposits, mints and returns STAR
ITreasury internal immutable treasury;
IBondDepository internal immutable depository;
uint public constant MAX_TOKENS = 12500000 * 1e9;
uint256 public tokensMinted;
uint256 public startTime;
bool public isActive;
bool public isCompleted;
uint256 public endTime;
constructor( address _star, address _treasury, address _depository )
{
tokensMinted = 0;
star = IERC20(_star);
treasury = ITreasury(_treasury);
depository = IBondDepository(_depository);
}
/* ========== MUTABLE FUNCTIONS ========== */
/**
* @notice allows wallet to mint STAR via the feb crowdsale
* @param _amount uint256
* @param _reserve address
*/
function MintStar(uint256 _amount, address _reserve) external {
uint256 minted = _crowdsaleMint(_amount, _reserve);
}
/**
* @notice logic for purchasing STAR
* @param _amount uint256
* @param _reserve address
* @return toSend_ uint256
*/
function _crowdsaleMint(uint256 _amount, address _reserve) internal returns (uint256 toSend_) {
require(activeSale(), "crowdsale is inactive");
toSend_ = treasury.deposit(msg.sender,_amount, _reserve, treasury.tokenValue(_reserve, _amount) * 75 / 100);
require(validTransaction(toSend_), "minting too many tokens");
tokensMinted += toSend_;
depository.crowdsalePurchase(toSend_);
emit StarMinted(msg.sender, _amount, _reserve);
}
function initialize() external onlyOwner {
isActive = true;
startTime = block.timestamp;
endTime = block.timestamp + 3 days;
emit CrowdsaleInitialized(msg.sender, startTime);
}
function completeSale() external onlyOwner {
isActive = false;
isCompleted = true;
}
function resetCrowdsale() external onlyOwner {
isActive = false;
isCompleted = false;
startTime = 0;
endTime = 0;
tokensMinted = 0;
}
function activeSale() public returns (bool) {
bool withinPeriod = block.timestamp >= startTime && block.timestamp <= endTime;
return isActive && withinPeriod;
}
function validTransaction(uint256 toSend_) internal returns (bool) {
bool validPurchase = tokensMinted + toSend_ <= MAX_TOKENS;
//bool nonZeroPurchase = msg.value != 0;
return validPurchase;
}
/* ========== VIEW FUNCTIONS ========== */
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
interface ITreasury {
function deposit(
address _from,
uint256 _amount,
address _token,
uint256 _profit
) external returns (uint256);
function withdraw(uint256 _amount, address _token) external;
function tokenValue(address _token, uint256 _amount) external view returns (uint256 value_);
function mint(address _recipient, uint256 _amount) external;
function manage(address _token, uint256 _amount) external;
function incurDebt(uint256 amount_, address token_) external;
function repayDebtWithReserve(uint256 amount_, address token_) external;
function excessReserves() external view returns (uint256);
function baseSupply() external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
interface IStaking {
function stake(
address _to,
uint256 _amount,
bool _rebasing,
bool _claim
) external returns (uint256);
function claim(address _recipient, bool _rebasing) external returns (uint256);
function forfeit() external returns (uint256);
function toggleLock() external;
function unstake(
address _to,
uint256 _amount,
bool _trigger,
bool _rebasing
) external returns (uint256);
function wrap(address _to, uint256 _amount) external returns (uint256 gBalance_);
function unwrap(address _to, uint256 _amount) external returns (uint256 sBalance_);
function rebase() external;
function index() external view returns (uint256);
function contractBalance() external view returns (uint256);
function totalStaked() external view returns (uint256);
function supplyInWarmup() external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
import "./IERC20.sol";
interface IBondDepository {
// Info about each type of market
struct Market {
uint256 capacity; // capacity remaining
IERC20 quoteToken; // token to accept as payment
bool capacityInQuote; // capacity limit is in payment token (true) or in OHM (false, default)
uint64 totalDebt; // total debt from market
uint64 maxPayout; // max tokens in/out (determined by capacityInQuote false/true, respectively)
uint64 sold; // base tokens out
uint256 purchased; // quote tokens in
}
// Info for creating new markets
struct Terms {
bool fixedTerm; // fixed term or fixed expiration
uint64 controlVariable; // scaling variable for price
uint48 vesting; // length of time from deposit to maturity if fixed-term
uint48 conclusion; // timestamp when market no longer offered (doubles as time when market matures if fixed-expiry)
uint64 maxDebt; // 9 decimal debt maximum in OHM
}
// Additional info about market.
struct Metadata {
uint48 lastTune; // last timestamp when control variable was tuned
uint48 lastDecay; // last timestamp when market was created and debt was decayed
uint48 length; // time from creation to conclusion. used as speed to decay debt.
uint48 depositInterval; // target frequency of deposits
uint48 tuneInterval; // frequency of tuning
uint8 quoteDecimals; // decimals of quote token
}
// Control variable adjustment data
struct Adjustment {
uint64 change;
uint48 lastAdjustment;
uint48 timeToAdjusted;
bool active;
}
/**
* @notice deposit market
* @param _bid uint256
* @param _amount uint256
* @param _maxPrice uint256
* @param _user address
* @param _referral address
* @return payout_ uint256
* @return expiry_ uint256
* @return index_ uint256
*/
function deposit(
uint256 _bid,
uint256 _amount,
uint256 _maxPrice,
address _user,
address _referral
)
external
returns (
uint256 payout_,
uint256 expiry_,
uint256 index_
);
function create(
IERC20 _quoteToken, // token used to deposit
uint256[3] memory _market, // [capacity, initial price]
bool[2] memory _booleans, // [capacity in quote, fixed term]
uint256[2] memory _terms, // [vesting, conclusion]
uint32[2] memory _intervals // [deposit interval, tune interval]
) external returns (uint256 id_);
function close(uint256 _id) external;
function setCrowdsale(address _contract) external;
function crowdsalePurchase (uint256 _payout) external returns (uint256);
function isLive(uint256 _bid) external view returns (bool);
function liveMarkets() external view returns (uint256[] memory);
function liveMarketsFor(address _quoteToken) external view returns (uint256[] memory);
function payoutFor(uint256 _amount, uint256 _bid) external view returns (uint256);
function marketPrice(uint256 _bid) external view returns (uint256);
function currentDebt(uint256 _bid) external view returns (uint256);
function debtRatio(uint256 _bid) external view returns (uint256);
function debtDecay(uint256 _bid) external view returns (uint64);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.7.5;
import "../interfaces/IOwnable.sol";
abstract contract Ownable is IOwnable {
address internal _owner;
address internal _newOwner;
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
constructor() {
_owner = msg.sender;
emit OwnershipPushed(address(0), _owner);
}
function owner() public view override returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
function renounceManagement() public virtual override onlyOwner {
emit OwnershipPulled(_owner, address(0));
_owner = address(0);
_newOwner = address(0);
}
function pushManagement(address newOwner_) public virtual override onlyOwner {
emit OwnershipPushed(_owner, newOwner_);
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require(msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled(_owner, _newOwner);
_owner = _newOwner;
_newOwner = address(0);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
interface IOwnable {
function owner() external view returns (address);
function renounceManagement() external;
function pushManagement(address newOwner_) external;
function pullManagement() external;
}
|
bool nonZeroPurchase = msg.value != 0;
|
function validTransaction(uint256 toSend_) internal returns (bool) {
bool validPurchase = tokensMinted + toSend_ <= MAX_TOKENS;
return validPurchase;
}
| 11,733,414
|
./full_match/5/0x6c8D0600CE043B4E909433723220F0BE1531C54A/sources/contracts/smart-wallet/managed/ManagedAccountFactory.sol
|
/// Returns the extension implementation address stored in router, for the given function.
|
View functions
function getImplementationForFunction(bytes4 _functionSelector) public view override returns (address) {
address impl = getExtensionForFunction(_functionSelector).implementation;
return impl != address(0) ? impl : defaultExtension;
}
| 1,960,376
|
pragma solidity ^0.8.8;
// SPDX-License-Identifier: MIT
/**
* @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;
}
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @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) external view returns (address);
/**
* @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) external view returns (uint256);
}
/*
* @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) {
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 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 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 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);
}
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
/**
* @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];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// 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);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// 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));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
/**
* @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(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
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);
}
}
interface IItemFactory {
// function rarityDecimal() external view returns (uint256);
function totalSupply(uint256 boxType) external view returns (uint256);
function addItem(
uint256 boxType,
uint256 itemId,
uint256 rarity,
uint256 itemInitialLevel,
uint256 itemInitialExperience
) external;
function getRandomItem(uint256 randomness, uint256 boxType)
external
view
returns (uint256 itemId);
function getItemInitialLevel(uint256[] memory boxTypes, uint256[] memory itemIds)
external
view
returns (uint256);
function getItemInitialExperience(uint256[] memory boxTypes, uint256[] memory itemIds)
external
view
returns (uint256);
event ItemAdded(
uint256 indexed boxType,
uint256 indexed itemId,
uint256 rarity,
uint256 itemInitialLevel,
uint256 itemInitialExperience
);
event ItemUpdated(
uint256 indexed boxType,
uint256 indexed itemId,
uint256 rarity,
uint256 itemInitialLevel,
uint256 itemInitialExperience
);
}
contract ItemFactoryManager {
IItemFactory public itemFactory;
event ItemFactoryUpdated(address itemFactory_);
constructor(address itemFactory_) {
_updateItemFactory(itemFactory_);
}
function _updateItemFactory(address itemFactory_) internal {
itemFactory = IItemFactory(itemFactory_);
emit ItemFactoryUpdated(itemFactory_);
}
}
/**
* @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);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev 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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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 {}
}
/**
* @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;
address private _potentialOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event OwnerNominated(address potentialOwner);
/**
* @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 Returns the address of the current potentialOwner.
*/
function potentialOwner() public view returns (address) {
return _potentialOwner;
}
/**
* @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 nominatePotentialOwner(address newOwner) public virtual onlyOwner {
_potentialOwner = newOwner;
emit OwnerNominated(newOwner);
}
function acceptOwnership () public virtual {
require(msg.sender == _potentialOwner, 'You must be nominated as potential owner before you can accept ownership');
emit OwnershipTransferred(_owner, _potentialOwner);
_owner = _potentialOwner;
_potentialOwner = address(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);
}
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
/**
* @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();
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @dev ERC721 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC721Pausable is ERC721, Pausable {
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
/**
* @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;
}
}
contract ChatPuppyNFTCore is
Ownable,
ERC721Enumerable,
ERC721Burnable,
ERC721Pausable
{
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdTracker;
uint256 private _cap;
struct Item {
bytes32 dna;
uint256 artifacts;
}
mapping(uint256 => Item) private _items;
mapping(uint256 => string) private _tokenURIs;
event CapUpdated(uint256 cap);
event UpdateTokenURI(uint256 indexed tokenId, string tokenURI);
event UpdateMetadata(uint256 indexed tokenId, bytes32 dna, uint256 artifacts);
event UpdateMetadata(uint256 indexed tokenId, uint256 artifacts);
constructor(
string memory name_,
string memory symbol_,
uint256 initialCap_
) ERC721(name_, symbol_) {
require(initialCap_ > 0, "ChatPuppyNFTCore: cap is 0");
_updateCap(initialCap_);
_tokenIdTracker.increment();
}
function _mint(address to_, uint256 tokenId_) internal virtual override {
require(
ERC721Enumerable.totalSupply() < cap(),
"ChatPuppyNFTCore: cap exceeded"
);
super._mint(to_, tokenId_);
}
function _updateCap(uint256 cap_) private {
_cap = cap_;
emit CapUpdated(cap_);
}
function _beforeTokenTransfer(
address from_,
address to_,
uint256 tokenId_
) internal virtual override(ERC721, ERC721Enumerable, ERC721Pausable) {
super._beforeTokenTransfer(from_, to_, tokenId_);
}
function exists(uint256 tokenId_) external view returns (bool) {
return _exists(tokenId_);
}
function cap() public view returns (uint256) {
return _cap;
}
function increaseCap(uint256 amount_) public onlyOwner {
require(amount_ > 0, "ChatPuppyNFTCore: amount is 0");
uint256 newCap = cap() + amount_;
_updateCap(newCap);
}
function mint(address to_) public onlyOwner returns (uint256) {
// We cannot just use balanceOf to create the new tokenId because tokens
// can be burned (destroyed), so we need a separate counter.
uint256 _tokenId = _tokenIdTracker.current();
_mint(to_, _tokenId);
_tokenIdTracker.increment();
return _tokenId;
}
/**
* @dev Batch mint
*/
function mintBatch(address to_, uint256 amount_) public onlyOwner {
require(amount_ > 0, "ChatPuppyNFT: amount_ is 0");
require(totalSupply() + amount_ <= cap(), "cap exceeded");
for (uint256 i = 0; i < amount_; i++) {
mint(to_);
}
}
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must be owner.
*/
function pause() public virtual onlyOwner {
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must be owner.
*/
function unpause() public virtual onlyOwner {
_unpause();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId_) public view virtual override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId_);
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId_) public view virtual override returns (string memory) {
require(
_exists(tokenId_),
"ChatPuppyNFTCore: URI query for nonexistent token"
);
return _tokenURIs[tokenId_];
}
function updateTokenMetaData(uint256 tokenId_, uint256 artifacts_) external onlyOwner {
require(_exists(tokenId_), "ChatPuppyNFTCore: tokeId not exists");
Item storage _info = _items[tokenId_];
_info.artifacts = artifacts_;
emit UpdateMetadata(tokenId_, artifacts_);
}
function updateTokenMetaData(uint256 tokenId_, uint256 artifacts_, bytes32 dna_) external onlyOwner {
require(_exists(tokenId_), "ChatPuppyNFTCore: tokeId not exists");
Item storage _info = _items[tokenId_];
_info.artifacts = artifacts_;
if (dna_ != 0 && _info.dna == 0) {
_info.dna = dna_;
}
emit UpdateMetadata(tokenId_, dna_, artifacts_);
}
function updateTokenURI(uint256 tokenId_, string calldata uri_) external {
require(_exists(tokenId_), "ChatPuppyNFTCore: tokeId not exists");
require((ownerOf(tokenId_) == _msgSender() && bytes(_tokenURIs[tokenId_]).length == 0)
|| _msgSender() == owner(), "ChatPuppyNFTCore: owner of nft can only set once, contract owner can set always");
_tokenURIs[tokenId_] = uri_;
emit UpdateTokenURI(tokenId_, uri_);
}
function tokenMetaData(uint256 tokenId_) external view returns (bytes32 _dna, uint256 _artifacts, string memory _hexArtifacts) {
_dna = _items[tokenId_].dna;
_artifacts = _items[tokenId_].artifacts;
_hexArtifacts = _items[tokenId_].artifacts.toHexString();
}
}
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);
}
interface VRFCoordinatorV2Interface {
/**
* @notice Get configuration relevant for making requests
* @return minimumRequestConfirmations global min for request confirmations
* @return maxGasLimit global max for request gas limit
* @return s_provingKeyHashes list of registered key hashes
*/
function getRequestConfig()
external
view
returns (
uint16,
uint32,
bytes32[] memory
);
/**
* @notice Request a set of random words.
* @param keyHash - Corresponds to a particular oracle job which uses
* that key for generating the VRF proof. Different keyHash's have different gas price
* ceilings, so you can select a specific one to bound your maximum per request cost.
* @param subId - The ID of the VRF subscription. Must be funded
* with the minimum subscription balance required for the selected keyHash.
* @param minimumRequestConfirmations - How many blocks you'd like the
* oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
* for why you may want to request more. The acceptable range is
* [minimumRequestBlockConfirmations, 200].
* @param callbackGasLimit - How much gas you'd like to receive in your
* fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
* may be slightly less than this amount because of gas used calling the function
* (argument decoding etc.), so you may need to request slightly more than you expect
* to have inside fulfillRandomWords. The acceptable range is
* [0, maxGasLimit]
* @param numWords - The number of uint256 random values you'd like to receive
* in your fulfillRandomWords callback. Note these numbers are expanded in a
* secure way by the VRFCoordinator from a single random value supplied by the oracle.
* @return requestId - A unique identifier of the request. Can be used to match
* a request to a response in fulfillRandomWords.
*/
function requestRandomWords(
bytes32 keyHash,
uint64 subId,
uint16 minimumRequestConfirmations,
uint32 callbackGasLimit,
uint32 numWords
) external returns (uint256 requestId);
/**
* @notice Create a VRF subscription.
* @return subId - A unique subscription id.
* @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
* @dev Note to fund the subscription, use transferAndCall. For example
* @dev LINKTOKEN.transferAndCall(
* @dev address(COORDINATOR),
* @dev amount,
* @dev abi.encode(subId));
*/
function createSubscription() external returns (uint64 subId);
/**
* @notice Get a VRF subscription.
* @param subId - ID of the subscription
* @return balance - LINK balance of the subscription in juels.
* @return reqCount - number of requests for this subscription, determines fee tier.
* @return owner - owner of the subscription.
* @return consumers - list of consumer address which are able to use this subscription.
*/
function getSubscription(uint64 subId)
external
view
returns (
uint96 balance,
uint64 reqCount,
address owner,
address[] memory consumers
);
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @param newOwner - proposed new owner of the subscription
*/
function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external;
/**
* @notice Request subscription owner transfer.
* @param subId - ID of the subscription
* @dev will revert if original owner of subId has
* not requested that msg.sender become the new owner.
*/
function acceptSubscriptionOwnerTransfer(uint64 subId) external;
/**
* @notice Add a consumer to a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - New consumer which can use the subscription
*/
function addConsumer(uint64 subId, address consumer) external;
/**
* @notice Remove a consumer from a VRF subscription.
* @param subId - ID of the subscription
* @param consumer - Consumer to remove from the subscription
*/
function removeConsumer(uint64 subId, address consumer) external;
/**
* @notice Cancel a subscription
* @param subId - ID of the subscription
* @param to - Where to send the remaining LINK to
*/
function cancelSubscription(uint64 subId, address to) external;
}
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness. It ensures 2 things:
* @dev 1. The fulfillment came from the VRFCoordinator
* @dev 2. The consumer contract implements fulfillRandomWords.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash). Create subscription, fund it
* @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface
* @dev subscription management functions).
* @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations,
* @dev callbackGasLimit, numWords),
* @dev see (VRFCoordinatorInterface for a description of the arguments).
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomWords method.
*
* @dev The randomness argument to fulfillRandomWords is a set of random words
* @dev generated from your requestId and the blockHash of the request.
*
* @dev If your contract could have concurrent requests open, you can use the
* @dev requestId returned from requestRandomWords to track which response is associated
* @dev with which randomness request.
* @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ.
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request. It is for this reason that
* @dev that you can signal to an oracle you'd like them to wait longer before
* @dev responding to the request (however this is not enforced in the contract
* @dev and so remains effective only in the case of unmodified oracle software).
*/
abstract contract VRFConsumerBaseV2 {
error OnlyCoordinatorCanFulfill(address have, address want);
address private immutable vrfCoordinator;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
*/
constructor(address _vrfCoordinator) {
vrfCoordinator = _vrfCoordinator;
}
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomWords the VRF output expanded to the requested number of words
*/
function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual;
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external {
if (msg.sender != vrfCoordinator) {
revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator);
}
fulfillRandomWords(requestId, randomWords);
}
}
// import "./lib/Bitmask.sol";
contract ChatPuppyNFTManagerV2 is
AccessControlEnumerable,
VRFConsumerBaseV2,
ItemFactoryManager
// Bitmask
{
using EnumerableSet for EnumerableSet.UintSet;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
bytes32 public constant CAP_MANAGER_ROLE = keccak256("CAP_MANAGER_ROLE");
bytes32 public constant CONTRACT_UPGRADER = keccak256("CONTRACT_UPGRADER");
bytes32 public constant NFT_UPGRADER = keccak256("NFT_UPGRADER");
ChatPuppyNFTCore public nftCore;
// uint256 private projectId = 0;
uint256 public boxPrice = 0;
// Mystery Box type
EnumerableSet.UintSet private _supportedBoxTypes;
mapping(uint256 => uint256[]) private _randomWords;// _randomnesses;
mapping(uint256 => uint256) private _requestIds;
mapping(uint256 => uint256) private _tokenIds;
VRFCoordinatorV2Interface public COORDINATOR;
uint256 public randomFee = 0;
address public feeAccount;
bytes32 private _keyHash = 0xd4bb89654db74673a187bd804519e65e3f71a52bc55f11da7601a13dcf505314;
uint32 private _callbackGasLimit = 500000;
uint16 private _requestConfirmations = 3; // Minimum confirmatons is 3
uint64 private _subscriptionId;
uint256[] public boxTypes = [2, 3, 4, 5, 6, 7]; // NFT Trait types
bool public canBuyAndMint = true;
bool public canUnbox = true;
event UnboxToken(uint256 indexed tokenId, uint256 indexed requestId);
event TokenFulfilled(uint256 indexed tokenId);
constructor(
address nftAddress_,
address itemFactory_,
uint256 boxPrice_,
uint64 subscriptionId_,
address vrfCoordinator_,
bytes32 keyHash_,
uint32 callbackGasLimit_,
uint16 requestConfirmations_)
VRFConsumerBaseV2(vrfCoordinator_)
ItemFactoryManager(itemFactory_) {
require(boxPrice_ > 0, "ChatPuppyNFTManager: box price can not be zero");
boxPrice = boxPrice_;
nftCore = ChatPuppyNFTCore(nftAddress_);
_supportedBoxTypes.add(1); // Mystery Box Type#1, Dragon
_supportedBoxTypes.add(2); // Mystery Box Type#2, Weapon
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
_setupRole(CAP_MANAGER_ROLE, _msgSender());
_setupRole(MANAGER_ROLE, _msgSender());
_setupRole(CONTRACT_UPGRADER, _msgSender());
_setupRole(NFT_UPGRADER, _msgSender());
// Initialize VRFRandomGenerator
COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator_);
_subscriptionId = subscriptionId_;
_keyHash = keyHash_;
_callbackGasLimit = callbackGasLimit_;
_requestConfirmations = requestConfirmations_;
}
modifier onlyTokenOwner(uint256 tokenId_) {
require(nftCore.ownerOf(tokenId_) == _msgSender(), "ChatPuppyNFTManager: caller is not owner");
_;
}
modifier onlyMysteryBox(uint256 tokenId_) {
(bytes32 _dna, ,) = nftCore.tokenMetaData(tokenId_);
require(_dna == 0, "ChatPuppyNFTManager: token is already unboxed");
_;
}
modifier onlyExistedToken(uint256 tokenId_) {
require(nftCore.exists(tokenId_), "ChatPuppyNFTManager: token does not exists");
_;
}
function _getBitMask(uint256 lsbIndex_, uint256 length_) private pure returns (uint256) {
return ((1 << length_) - 1) << lsbIndex_;
}
function _clearBits(
uint256 data_,
uint256 lsbIndex_,
uint256 length_) private pure returns (uint256) {
return data_ & (~_getBitMask(lsbIndex_, length_));
}
function _addArtifactValue(
uint256 artifacts_,
uint256 lsbIndex_,
uint256 length_,
uint256 artifactValue_) private pure returns (uint256) {
return((artifactValue_ << lsbIndex_) & _getBitMask(lsbIndex_, length_)) | _clearBits(artifacts_, lsbIndex_, length_);
}
/**
* @dev Transfer the ownership of NFT
*/
function upgradeNFTCoreOwner(address newOwner_) external onlyRole(CONTRACT_UPGRADER) {
nftCore.transferOwnership(newOwner_);
}
/**
* @dev update nft core contract
*/
function updateNFTCoreContract(address newAddress_) external onlyRole(CONTRACT_UPGRADER) {
nftCore = ChatPuppyNFTCore(newAddress_);
}
/**
* @dev Increase the cap of NFT
*/
function increaseCap(uint256 amount_) external onlyRole(CAP_MANAGER_ROLE) {
nftCore.increaseCap(amount_);
}
/**
* @dev Update status of buy and mint
*/
function setCanBuyAndMint(bool _status) external onlyRole(MANAGER_ROLE) {
canBuyAndMint = _status;
}
/**
* @dev Update status of unbox
*/
function setCanUnbox(bool _status) external onlyRole(MANAGER_ROLE) {
canUnbox = _status;
}
/**
* @dev update mystery box price
*/
function updateBoxPrice(uint256 price_) external onlyRole(MANAGER_ROLE) {
require(price_ > 0, "ChatPuppyNFTManager: box price can not be zero");
boxPrice = price_;
}
/**
* @dev pause NFT transaction
*/
function pause() external onlyRole(PAUSER_ROLE) {
nftCore.pause();
}
/**
* @dev restart NFT transaction
*/
function unpause() external onlyRole(PAUSER_ROLE) {
nftCore.unpause();
}
/**
* @dev Update Item Factory
*/
function updateItemFactory(address itemFactory_) public onlyRole(CONTRACT_UPGRADER) {
require(itemFactory_ != address(0), "ChatPuppyNFTManager: itemFactory_ is the zero address");
_updateItemFactory(itemFactory_);
}
/**
* @dev Update ChainLink Random VRFCoordinatorV2
*/
function updateVRFCoordinatorV2(address vrfCoordinator_) public onlyRole(CONTRACT_UPGRADER) {
require(vrfCoordinator_ != address(0), "ChatPuppyNFTManager: vrfCoordinator_ is the zero address");
COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator_);
}
function updateKeyHash(bytes32 keyHash_) public onlyRole(CONTRACT_UPGRADER) {
_keyHash = keyHash_;
}
function updateSubscriptionId(uint64 subscriptionId_) public onlyRole(CONTRACT_UPGRADER) {
_subscriptionId = subscriptionId_;
}
function updateCallbackGasLimit(uint32 callbackGasLimit_) public onlyRole(CONTRACT_UPGRADER) {
require(callbackGasLimit_ >= 100000, "ChatPuppyNFTManager: Suggest to set 100000 mimimum");
_callbackGasLimit = callbackGasLimit_;
}
function updateRequestConfirmations(uint16 requestConfirmations_) public onlyRole(CONTRACT_UPGRADER) {
_requestConfirmations = requestConfirmations_;
}
/**
* @dev Withdraw ETH/BNB from NFTManager contracts
*/
function withdraw(address to_, uint256 amount_) public onlyRole(MANAGER_ROLE) {
require(to_ != address(0), "ChatPuppyNFTManager: withdraw address is the zero address");
require(amount_ > uint256(0), "ChatPuppyNFTManager: withdraw amount is zero");
uint256 balance = address(this).balance;
require(balance >= amount_, "ChatPuppyNFTManager: withdraw amount must smaller than balance");
(bool sent, ) = to_.call{value: amount_}("");
require(sent, "ChatPuppyNFTManager: Failed to send Ether");
}
/**
* Buy and mint
*/
function buyAndMint() public payable {
require(canBuyAndMint, "ChatPuppyNFTManager: not allowed to buy and mint");
require(msg.value >= boxPrice, "ChatPuppyNFTManager: payment is not enough");
_mint(_msgSender());
}
/**
* Buy set of mystery box and mint
*/
function buyAndMintBatch(uint256 amount_) public payable {
require(canBuyAndMint, "ChatPuppyNFTManager: not allowed to buy and mint");
require(amount_ > 0, "ChatPuppyNFTManager: amount_ is 0");
require(msg.value >= boxPrice * amount_, "ChatPuppyNFTManager: Batch purchase payment is not enough");
for (uint256 i = 0; i < amount_; i++) {
buyAndMint();
}
}
/**
* Buy, mint and unbox
*/
function buyMintAndUnbox() public payable {
require(canBuyAndMint, "ChatPuppyNFTManager: not allowed to buy and mint");
require(msg.value >= boxPrice, "ChatPuppyNFTManager: payment is not enough");
uint256 _tokenId = _mint(_msgSender());
unbox(_tokenId);
}
/**
* @dev Mint NFT with boxType
*/
function mint(address to_) public onlyRole(MINTER_ROLE) {
_mint(to_);
}
/**
* @dev Batch mint
*/
function mintBatch(address to_, uint256 amount_) external onlyRole(MINTER_ROLE) {
require(amount_ > 0, "ChatPuppyNFTManager: amount_ is 0");
require(nftCore.totalSupply() + amount_ <= nftCore.cap(), "cap exceeded");
for (uint256 i = 0; i < amount_; i++) {
_mint(to_);
}
}
function _mint(address to_) private returns(uint256) {
return nftCore.mint(to_);
}
function boxStatus(uint256 tokenId_) public view returns(uint8) {
if(_requestIds[tokenId_] > uint256(0) && _randomWords[tokenId_].length == 0) return 2; // unboxing
else if(_requestIds[tokenId_] > uint256(0) && _randomWords[tokenId_].length > 0) return 1; //unboxed
else return 0; // can unbox
}
/**
* @dev Unbox mystery box
* This is a payable function
*/
function unbox(uint256 tokenId_) public payable
onlyExistedToken(tokenId_)
onlyTokenOwner(tokenId_)
onlyMysteryBox(tokenId_)
{
require(canUnbox, "ChatPuppyNFTManager: unbox is forbidden");
require(boxStatus(tokenId_) == 0, "ChatPuppyNFTManager: token is unboxing or unboxed");
require(boxTypes.length > 0, "ChatPuppyNFTManager: boxTypes is not set");
_takeRandomFee();
uint256 requestId_ = COORDINATOR.requestRandomWords(
_keyHash,
_subscriptionId,
_requestConfirmations,
_callbackGasLimit,
1
);
_requestIds[tokenId_] = requestId_;
_tokenIds[requestId_] = tokenId_;
emit UnboxToken(tokenId_, requestId_);
}
/**
* After unbox and requestRandomNumber, this fulfillRandomness callback function will be called automaticly
* and update random metadata for NFT
*
* For getting random number by ChainLink VRF, refer to: https://docs.chain.link/docs/intermediates-tutorial/
*
* ArtifactValue format:
* 0~7: boxType#1(trait#1), len=8, 0-255
* 8~15: boxType#2, len=8, 0-255
* 16~23: boxType#3, len=8, 0-255
* 24~31: boxType#4, len=8, 0-255
* 32~39: boxType#5, len=8, 0-255
* 40~47: boxType#6, len=8, 0-255
* 48~63: level, len=16, 0-65535
* 64~79: experience, len=16, 0-65535
*
* dna format:
* dna = bytes32(keccak256(abi.encodePacked(tokenId_, randomness_)));
*
*/
function expand(uint256 randomValue, uint256 n) public pure returns (uint256[] memory){
uint256[] memory expandedValues = new uint256[](n);
for(uint256 i = 0; i < n; i++) expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i)));
return expandedValues;
}
function randomWords(uint256 tokenId_) public view returns(uint256, uint256[] memory) {
return (_requestIds[tokenId_], _randomWords[tokenId_]);
}
function fulfillRandomWords(uint256 requestId_, uint256[] memory randomWords_) internal override {
uint256 tokenId_ = _tokenIds[requestId_];
(bytes32 _dna, uint256 _artifacts, ) = nftCore.tokenMetaData(tokenId_);
uint256 randomness_ = randomWords_[0];
uint256[] memory randomWords__ = expand(randomness_, 6); // callbackGas一定要足够!!!
_dna = bytes32(keccak256(abi.encodePacked(tokenId_, randomness_)));
uint256[] memory _itemIds = new uint256[](boxTypes.length);
for(uint256 i = 0; i < boxTypes.length; i++) {
uint256 _itemId = itemFactory.getRandomItem(
randomWords__[i],
boxTypes[i]
);
_itemIds[i] = _itemId;
_artifacts = _addArtifactValue(_artifacts, i * 8, 8, _itemId); // add itemId
}
_artifacts = _addArtifactValue(_artifacts, boxTypes.length * 8, 16, itemFactory.getItemInitialLevel(boxTypes, _itemIds)); // add level
_artifacts = _addArtifactValue(_artifacts, boxTypes.length * 8 + 16, 16, itemFactory.getItemInitialExperience(boxTypes, _itemIds)); // add exeperience
_randomWords[tokenId_] = randomWords__;
nftCore.updateTokenMetaData(tokenId_, _artifacts, _dna);
emit TokenFulfilled(tokenId_);
}
function supportedBoxTypes() external view returns (uint256[] memory) {
return _supportedBoxTypes.values();
}
function upgradeNFT(uint256 tokenId_, uint256 artifacts_) external onlyRole(NFT_UPGRADER) {
nftCore.updateTokenMetaData(tokenId_, artifacts_);
}
function updateRandomFee(uint256 randomFee_) public onlyRole(MANAGER_ROLE) {
randomFee = randomFee_;
}
function updateFeeAccount(address feeAccount_) public onlyRole(MANAGER_ROLE) {
require(feeAccount_ != address(0), "ChatPuppyNFTManager: feeAccount can not be zero address");
feeAccount = feeAccount_;
}
function updateBoxTypes(uint256[] calldata boxTypes_) external onlyRole(MANAGER_ROLE) {
boxTypes = boxTypes_;
}
function updateTokenURI(uint256 tokenId_, string calldata uri_) external onlyRole(NFT_UPGRADER) {
nftCore.updateTokenURI(tokenId_, uri_);
}
function _takeRandomFee() internal {
if (randomFee > 0) {
require(msg.value >= randomFee, "ChatPuppyNFTManager: insufficient fee");
require(feeAccount != address(0), "ChatPuppyNFTManager: feeAccount is the zero address");
(bool success, ) = address(feeAccount).call{value: msg.value}(new bytes(0));
require(success, "ChatPuppyNFTManager: fee required");
}
}
}
|
Withdraw ETH/BNB from NFTManager contracts/
|
function withdraw(address to_, uint256 amount_) public onlyRole(MANAGER_ROLE) {
require(to_ != address(0), "ChatPuppyNFTManager: withdraw address is the zero address");
require(amount_ > uint256(0), "ChatPuppyNFTManager: withdraw amount is zero");
uint256 balance = address(this).balance;
require(balance >= amount_, "ChatPuppyNFTManager: withdraw amount must smaller than balance");
require(sent, "ChatPuppyNFTManager: Failed to send Ether");
}
| 1,129,224
|
// SPDX-License-Identifier: CC0
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import './Structures.sol';
library Utils {
bytes32 public constant ZERO = bytes32(0);
function hashTransaction(Structures.Transaction memory t) internal pure returns(bytes32) {
return keccak256(
abi.encodePacked(
t.value,
t.historicRootBlockNumberL2,
t.transactionType,
t.tokenType,
t.tokenId,
t.ercAddress, // Take in as bytes32 for consistent hashing
t.recipientAddress,
t.commitments,
t.nullifiers,
t.compressedSecrets,
t.proof
)
);
}
function hashBlock(Structures.Block memory b, Structures.Transaction[] memory t)
internal
pure
returns (bytes32)
{
return keccak256(abi.encode(b, t));
}
function compressG1(uint256 x, uint256 y) internal pure returns (uint256) {
// compute whether y is odd or even and multiply by 2**255
uint256 parity =
0x8000000000000000000000000000000000000000000000000000000000000000 * (y % 2);
// add the parity bit to the x cordinate (x,y are 254 bits long - the final
// number is 256 bits to fit with an Ethereum word)
return parity + x;
}
function compressG2(
uint256 xr,
uint256 xi,
uint256 yr,
uint256 yi
) internal pure returns (uint256, uint256) {
return (compressG1(xr, yr), compressG1(xi, yi));
}
function compressProof(uint256[8] memory proof) internal pure returns (uint256[4] memory) {
uint256 a = compressG1(proof[0], proof[1]);
(uint256 rb, uint256 ib) = compressG2(proof[2], proof[3], proof[4], proof[5]);
uint256 c = compressG1(proof[6], proof[7]);
return [a, rb, ib, c];
}
// counts the number of non-zero values (useful for counting real commitments and nullifiers)
function countNonZeroValues(bytes32[2] memory vals) internal pure returns(uint) {
uint count;
if (vals[0] != ZERO) count++;
if (vals[1] != ZERO) count++;
return count;
}
// filters the number of non-zero values (useful for getting real commitments and nullifiers)
function filterNonZeroValues(bytes32[2] memory vals) internal pure returns(bytes32[] memory) {
bytes32[] memory filtered = new bytes32[](countNonZeroValues(vals));
uint count;
if (vals[0] != ZERO) filtered[count++] = vals[0]; // a bit faster than looping?
if (vals[1] != ZERO) filtered[count++] = vals[1];
return filtered;
}
// counts the number of non-zero commitments in a block containing the ts transactions)
function countCommitments(Structures.Transaction[] memory ts) internal pure returns(uint) {
uint count;
for (uint i = 0; i < ts.length; i++) {
count += countNonZeroValues(ts[i].commitments);
}
return count;
}
// filters the non-zero commitments in a block containing the ts transactions)
function filterCommitments(Structures.Transaction[] memory ts) internal pure returns(bytes32[] memory) {
bytes32[] memory filtered = new bytes32[](countCommitments(ts));
uint count;
for (uint i = 0; i < ts.length; i++) {
if (ts[i].commitments[0] != ZERO) filtered[count++] = ts[i].commitments[0];
if (ts[i].commitments[1] != ZERO) filtered[count++] = ts[i].commitments[1];
}
return filtered;
}
// gathers public inputs for each tx type
// required now we have removed the publicInputHash
function getPublicInputs(Structures.Transaction calldata ts, uint256[2] memory roots) internal pure returns(uint256[] memory inputs) {
// uint256[] memory inputs = new uint256[](countPublicInputs(ts));
if (ts.transactionType == Structures.TransactionTypes.DEPOSIT) {
inputs = getDepositInputs(ts);
} else if (ts.transactionType == Structures.TransactionTypes.SINGLE_TRANSFER) {
inputs = getSingleTransferInputs(ts, roots);
} else if (ts.transactionType == Structures.TransactionTypes.DOUBLE_TRANSFER) {
inputs = getDoubleTransferInputs(ts, roots);
} else {
inputs = getWithdrawInputs(ts, roots);
}
}
function getDepositInputs(Structures.Transaction calldata ts) internal pure returns(uint256[] memory) {
uint256[] memory inputs = new uint256[](4);
inputs[0] = uint256(ts.ercAddress);
inputs[1] = uint256(ts.tokenId);
inputs[2] = ts.value;
inputs[3] = uint256(ts.commitments[0]);
return inputs;
}
function getSingleTransferInputs(Structures.Transaction calldata ts, uint256[2] memory roots) internal pure returns(uint256[] memory) {
uint256[] memory inputs = new uint256[](12);
inputs[0] = uint256(ts.ercAddress);
inputs[1] = uint256(ts.commitments[0]);
inputs[2] = uint256(ts.nullifiers[0]);
inputs[3] = roots[0];
for (uint i = 4; i < 12; i++) {
inputs[i] = uint256(ts.compressedSecrets[i-4]);
}
return inputs;
}
function getWithdrawInputs(Structures.Transaction calldata ts, uint256[2] memory roots) internal pure returns(uint256[] memory) {
uint256[] memory inputs = new uint256[](16);
inputs[0] = uint256(ts.ercAddress);
inputs[1] = uint256(ts.tokenId);
inputs[2] = ts.value;
inputs[3] = uint256(ts.nullifiers[0]);
inputs[4] = uint256(ts.recipientAddress);
inputs[5] = roots[0];
return inputs;
}
function getDoubleTransferInputs(Structures.Transaction calldata ts, uint256[2] memory roots) internal pure returns(uint256[] memory) {
uint256[] memory inputs = new uint256[](6);
inputs[0] = uint256(ts.ercAddress);
inputs[1] = uint256(ts.ercAddress);
inputs[2] = uint256(ts.commitments[0]);
inputs[3] = uint256(ts.commitments[1]);
inputs[4] = uint256(ts.nullifiers[0]);
inputs[5] = uint256(ts.nullifiers[1]);
inputs[6] = roots[0];
inputs[7] = roots[1];
for (uint i = 8; i < 16; i++) {
inputs[i] = uint256(ts.compressedSecrets[i-8]);
}
return inputs;
}
}
|
gathers public inputs for each tx type required now we have removed the publicInputHash uint256[] memory inputs = new uint256[](countPublicInputs(ts));
|
function getPublicInputs(Structures.Transaction calldata ts, uint256[2] memory roots) internal pure returns(uint256[] memory inputs) {
if (ts.transactionType == Structures.TransactionTypes.DEPOSIT) {
inputs = getDepositInputs(ts);
inputs = getSingleTransferInputs(ts, roots);
inputs = getDoubleTransferInputs(ts, roots);
inputs = getWithdrawInputs(ts, roots);
}
}
| 7,274,913
|
// SPDX-License-Identifier: None
// Created by 256bit.io - 2021/2022
pragma solidity ^0.8.0;
import "ERC721Enumerable.sol";
import "OwnerOrAuthorized.sol";
import "CryptoCardsMessages.sol";
import "CryptoCardsStorage.sol";
import "CryptoCardsFactory.sol";
contract CryptoCards is ERC721Enumerable, OwnerOrAuthorized {
using Strings for uint256;
bool public paused;
CryptoCardsMessages public messages;
CryptoCardsStorage public store;
CryptoCardsFactory public factory;
event CardsMinted(address to, uint256 symbol, uint256[] ids);
event DeckMinted(address to, uint256 symbol);
event HandMinted(address to, uint256[5] ids, uint256 handId);
event ModifiedCardMinted(address to, uint256 id);
constructor(
string memory _name,
string memory _symbol,
address _messages,
address _storage,
address _factory
) ERC721(_name, _symbol) {
messages = CryptoCardsMessages(_messages);
store = CryptoCardsStorage(_storage);
factory = CryptoCardsFactory(_factory);
}
// Internal
function _baseURI() internal view virtual override returns (string memory) {
return store.baseURI();
}
function _mintCards(
address _to,
uint256 _mintAmount,
uint256 _symbol,
uint256 _modifierCard
) internal {
uint256[] memory cardIds = factory.createCards(
_mintAmount,
_symbol,
_modifierCard
);
for (uint256 i = 0; i < cardIds.length; i++) {
_safeMint(_to, cardIds[i]);
}
emit CardsMinted(_to, _symbol, cardIds);
}
function _addCreatorRewards(
uint256 _symbol,
uint256 _modifierCard,
uint256 _mintingCost
) internal {
uint32 rewardPercentage = store.rewardPercentage();
uint256 rewardAmount = (_mintingCost * rewardPercentage) / 100;
// If card(s) were minted using modifier card then add
// reward amount to modifier card creator's balance (excluding contract owner)
if (_modifierCard > 0) {
address creator = store.getModifierCardCreator(_modifierCard);
if (creator != address(0) && creator != owner()) {
store.addCreatorRewardTransaction(
creator,
_modifierCard,
0,
rewardAmount,
0
);
}
} else {
// Otherwise add to reward amount to symbol creator's balance (excluding contract owner)
address creator = store.getSymbolCreator(_symbol);
if (creator != address(0) && creator != owner()) {
store.addCreatorRewardTransaction(
creator,
0,
_symbol,
rewardAmount,
0
);
}
}
}
function _checkMintingParams(address _to, uint256 _mintCost) internal {
if (msg.sender != owner()) {
require(!paused, messages.notAvailable());
require(msg.value >= _mintCost, messages.notEnoughFunds());
}
require(_to != address(0), messages.zeroAddress());
}
// Public
function burn(uint256 _tokenId) public {
require(!paused, messages.notAvailable());
require(ownerOf(_tokenId) == msg.sender, messages.mustBeOwner());
// Hand?
if (store.getHandOwner(_tokenId) == msg.sender) {
uint256[5] memory hand = store.getHandCards(_tokenId);
// Re-allocate cards back to sender
for (uint256 i = 0; i < hand.length; i++) {
_safeMint(msg.sender, hand[i]);
}
store.setHandOwner(_tokenId, address(0));
store.setHandCards(
_tokenId,
[uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)]
);
}
_burn(_tokenId);
}
function mintCards(
address _to,
uint256 _mintAmount,
uint256 _symbol,
uint256 _modifierCard
) public payable {
uint256 mintingCost = _modifierCard > 0
? (store.cardCost() * 2 * _mintAmount)
: (store.cardCost() * _mintAmount);
_checkMintingParams(_to, mintingCost);
require(store.getSymbolInUse(_symbol), messages.symbolNotFound());
if (_modifierCard > 0) {
require(
ownerOf(_modifierCard) == msg.sender,
messages.mustBeOwner()
);
}
_mintCards(_to, _mintAmount, _symbol, _modifierCard);
_addCreatorRewards(_symbol, _modifierCard, mintingCost);
}
function mintDeck(address _to, uint256 _symbol) public payable {
_checkMintingParams(_to, store.deckCost());
if (msg.sender != owner()) {
require(store.getDeckMintUnlocking() == 0, messages.notAvailable());
}
require(!store.getSymbolInUse(_symbol), messages.symbolInUse());
// Add new symbol
store.addSymbol(_to, _symbol);
// Create initial shuffled deck
factory.createDeck(_symbol);
// Mint cards to new deck owner
_mintCards(_to, store.maxMintAmount(), _symbol, 0);
store.resetDeckMintUnlocking();
emit DeckMinted(_to, _symbol);
}
function mintHand(address _to, uint256[5] memory _tokenIds) public payable {
_checkMintingParams(_to, store.handCost());
uint256 supply = store.getTotalCards();
require(supply + 1 <= store.maxSupply(), messages.exceedsSupply());
require(_tokenIds.length == 5, messages.fiveCardsRequired());
// Check that the sender is the owner of all the cards
for (uint256 i = 0; i < _tokenIds.length; i++) {
require(_tokenIds[i] > 0, messages.fiveCardsRequired());
require(
ownerOf(_tokenIds[i]) == msg.sender,
messages.mustBeOwner()
);
}
// Save tokenIds of cards in the data property
uint256 data = (_tokenIds[0] & 0xFFFFFF) |
((_tokenIds[1] & 0xFFFFFF) << 24) |
((_tokenIds[2] & 0xFFFFFF) << 48) |
((_tokenIds[3] & 0xFFFFFF) << 72) |
((_tokenIds[4] & 0xFFFFFF) << 96);
uint256 handTokenId = store.addCard(
factory.createCard(DecodedCard(HAND_CARD, 0, 0, 0, 0, 0, 0), data)
);
_safeMint(_to, handTokenId);
// Burn cards so that they cannot be minted into a hand again.
for (uint256 i = 0; i < _tokenIds.length; i++) {
_burn(_tokenIds[i]);
}
store.setHandOwner(handTokenId, _to);
// Save the tokenIds that form the hand so they can be re-instated if the hand is ever burnt
store.setHandCards(handTokenId, _tokenIds);
emit HandMinted(_to, _tokenIds, handTokenId);
}
function mintModifiedCard(
address _to,
uint256 _originalCard,
uint256 _modifierCard
) public payable {
_checkMintingParams(_to, store.cardCost() * 2);
require(ownerOf(_originalCard) == msg.sender, messages.mustBeOwner());
require(ownerOf(_modifierCard) == msg.sender, messages.mustBeOwner());
uint256 cardId = factory.createModifiedCard(
_originalCard,
_modifierCard
);
_safeMint(_to, cardId);
_addCreatorRewards(0, _modifierCard, store.cardCost() * 2);
emit ModifiedCardMinted(_to, cardId);
}
function mintModifierCard(
address _to,
string memory _name,
uint256 _value,
uint256 _background,
uint256 _foreground,
uint256 _color,
uint256 _flags,
bytes memory _data
) public payable returns (uint256) {
_checkMintingParams(_to, store.modifierCost());
require(bytes(_name).length > 0, messages.nameRequired());
require(
store.getModifierCardIdByName(_name) == 0,
messages.modifierNameAlreadyInUse()
);
require(_data.length <= 256, messages.dataLengthExceeded());
uint256 newCardId = factory.createModifierCard(
_value,
_background,
_foreground,
_color,
_flags
);
_safeMint(_to, newCardId);
store.addModifierCard(newCardId, _to, _name, _data);
return newCardId;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), messages.erc721InvalidTokenId());
bool usePermanentStorage = store.getUsePermanentStorage(tokenId);
string memory currentBaseURI = usePermanentStorage
? store.permanentStorageBaseURI()
: _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
usePermanentStorage
? store.permanentStorageExtension()
: store.baseExtension()
)
)
: "";
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i = 0; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function getCreatorRewardsBalance(address _creator)
public
view
returns (uint256)
{
return store.getCreatorRewardsBalance(_creator);
}
function getCreatorRewards(address _creator)
public
view
returns (Reward[] memory)
{
return store.getCreatorRewards(_creator);
}
function withdrawRewardBalance() public payable {
uint256 contractBalance = address(this).balance;
uint256 callerRewards = getCreatorRewardsBalance(msg.sender);
require(callerRewards < contractBalance, messages.notEnoughFunds());
store.addCreatorRewardTransaction(msg.sender, 0, 0, 0, callerRewards);
require(payable(msg.sender).send(callerRewards));
}
// Only owner
function setPaused(bool _value) public onlyOwner {
paused = _value;
}
function getNetBalance() public view onlyOwner returns (uint256) {
uint256 contractBalance = address(this).balance;
uint256 totalCreatorRewards = store.getTotalRewardsBalance();
return contractBalance - totalCreatorRewards;
}
function withdrawNetBalance() public payable onlyOwner {
uint256 ownerBalance = getNetBalance();
require(ownerBalance > 0, messages.notEnoughFunds());
require(payable(msg.sender).send(ownerBalance));
}
function withdraw() public payable onlyOwner {
require(payable(msg.sender).send(address(this).balance));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "ERC721.sol";
import "IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC721.sol";
import "IERC721Receiver.sol";
import "IERC721Metadata.sol";
import "Address.sol";
import "Context.sol";
import "Strings.sol";
import "ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "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;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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: None
// Created by 256bit.io - 2021/2022
pragma solidity ^0.8.0;
import "Ownable.sol";
contract OwnerOrAuthorized is Ownable {
mapping(address => bool) private _authorized;
event AuthorizationAdded(address indexed addressAdded);
event AuthorizationRemoved(address addressRemoved);
constructor() Ownable() {
_authorized[msg.sender] = true;
}
/**
* @dev Throws if called by any account other than an authorized user (includes owner).
*/
modifier onlyAuthorized() {
require(
checkAuthorization(_msgSender()),
"OwnOwnerOrAuthorized: caller is not authorized"
);
_;
}
function addAuthorization(address _address) public onlyOwner {
_authorized[_address] = true;
emit AuthorizationAdded(_address);
}
function removeAuthorization(address _address) public {
require(
owner() == _msgSender() || _authorized[_address] == true,
"OwnOwnerOrAuthorized: caller is not authorized"
);
delete _authorized[_address];
emit AuthorizationRemoved(_address);
}
function checkAuthorization(address _address) public view returns (bool) {
return owner() == _address || _authorized[_address] == true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: None
// Created by 256bit.io - 2021/2022
pragma solidity ^0.8.0;
contract CryptoCardsMessages {
string public notAvailable = "Feature not currently available";
string public mintAmount = "Mint Amount";
string public exceedsSupply = "Supply exceeded";
string public exceedsDeckSupply = "Deck supply exceeded";
string public fiveCardsRequired = "Five cards required";
string public zeroAddress = "Zero address";
string public mustBeOwner = "Must be owner";
string public notEnoughFunds = "Not enough funds";
string public existingModifier = "Modifier exists";
string public nameRequired = "Name required";
string public modifierUsage = "Modifier usage exceeded";
string public modifierNotFound = "Modifier not found";
string public erc721InvalidTokenId = "URI query for nonexistent token";
string public symbolInUse = "Symbol already exists";
string public symbolNotFound = "Symbol not found";
string public missingShuffledDeck = "Missing shuffled deck for symbol";
string public modifierDataFull = "The card cannot accept further modifiers";
string public modifierNameAlreadyInUse =
"The specified name is already in use";
string public dataLengthExceeded = "Data length (256 bytes) exceeded";
}
// SPDX-License-Identifier: None
// Created by 256bit.io - 2021/2022
pragma solidity ^0.8.0;
import "OwnerOrAuthorized.sol";
uint256 constant MODIFIER_CARD = 0x40;
uint256 constant HAND_CARD = 0x20;
uint256 constant BITOFFSET_SUIT = 8;
uint256 constant BITOFFSET_BACKGROUND = 16;
uint256 constant BITOFFSET_FOREGROUND = 48;
uint256 constant BITOFFSET_COLOR = 80;
uint256 constant BITOFFSET_SYMBOL = 112;
uint256 constant BITOFFSET_FLAGS = 144;
uint256 constant DEFAULT_BACKGROUND = 0xff00a300;
uint256 constant DEFAULT_MODIFIER_BACKGROUND = 0xff1a1a1a;
uint256 constant DEFAULT_FOREGROUND = 0xff000000;
uint256 constant DEFAULT_COLOR = 0xffffffff;
uint256 constant FLAGS_SET_BACKGROUND = 1;
uint256 constant FLAGS_SET_FOREGROUND = 2;
uint256 constant FLAGS_SET_COLOR = 4;
uint256 constant FLAGS_DATA_APPEND = 8;
bytes constant PRE_SHUFFLED_DECK = hex"190E0F1E2722111D02040B2E13331209150100240A180D16321B25260C312A07282C1C0820142B101A17293006052F2D23211F03";
/* attributes = [
bytes 0: value 0..0xC = Card face value | 0x40 = Modifier Card | 0x20 = Hand Card
bytes 1: suit
bytes 2..5: background
bytes 6..9: foreground
bytes 10..13: color
bytes 14..17: symbol
bytes 18..31: modifier flags; on a modifier card this specifies how the data will be applied:
0x1 = background copied from modifier card
0x2 = foreground copied from modifier card
0x4 = color copied from modifier card
0x8 = modifiers will be appended with modifier card id instead of overwritten
]
modifiers: [32 bytes] essentially an array of modifier ids (16 bit)
*/
struct Card {
uint256 attributes;
uint256 modifiers;
}
struct ModifierCard {
address creator;
uint256 usageCount;
string name;
bytes data; // Seems to be a 256 byte limit??
}
struct Reward {
uint256 timestamp;
uint256 modifierCardId;
uint256 symbolId;
int256 value;
}
contract CryptoCardsStorage is OwnerOrAuthorized {
bytes private preShuffledDeck = PRE_SHUFFLED_DECK;
string public baseURI;
string public baseExtension;
string public permanentStorageBaseURI;
string public permanentStorageExtension;
uint256 public cardCost = 0.1 ether;
uint256 public handCost = 1 ether;
uint256 public deckCost = 10 ether;
uint256 public modifierCost = 2 ether;
uint256 private deckMintUnlocking = 100;
uint256 public defaultDeckMintUnlocking = 200;
uint32 public maxCardsPerDeck = 1000;
uint32 public maxModifierUsage = 100;
uint32 public maxSupply = 65535; // Hard limit due to 16 bit numbers use to store modifier ids on cards
uint32 public maxMintAmount = 10;
uint32 public rewardPercentage = 50;
Card[] public cards;
uint256[] public symbols;
uint256[] public modifiers;
address[] public creators;
// Mapping hand tokenId to owner address
mapping(uint256 => address) public handOwners;
// Mapping hand tokenId to card tokenIds used to mint hand
mapping(uint256 => uint256[5]) private handCards;
// Mapping deck => card count
mapping(uint256 => uint256) public deckCardCounts;
// Mapping modifier card id to data
mapping(uint256 => ModifierCard) public modifierCards;
// Mapping modifier card name to id
mapping(string => uint256) public modifierCardNames;
// Mapping symbol in use
mapping(uint256 => bool) private symbolInUse;
// Mapping symbol to creator
mapping(uint256 => address) private symbolCreators;
// Mapping creator to rewards
mapping(address => Reward[]) private creatorRewards;
// Mapping creator to reward balance
mapping(address => uint256) private creatorRewardsBalance;
// Mapping creator to known
mapping(address => bool) private knownCreators;
// Mapping symbol to shuffled deck
mapping(uint256 => bytes) private shuffledDecks;
// Mapping tokenId to TokenUri uses permanent storage
mapping(uint256 => bool) public usePermanentStorage;
constructor(string memory _initBaseURI, string memory _initExtension)
OwnerOrAuthorized()
{
baseURI = _initBaseURI;
baseExtension = _initExtension;
permanentStorageBaseURI = _initBaseURI;
permanentStorageExtension = _initExtension;
}
function addCard(Card memory _card)
external
onlyAuthorized
returns (uint256)
{
cards.push(_card);
uint256 symbol = (_card.attributes >> BITOFFSET_SYMBOL) & 0xFFFFFFFF;
deckCardCounts[symbol]++;
return cards.length - 1;
}
function addSymbol(address _creator, uint256 _symbol)
external
onlyAuthorized
{
if (!symbolInUse[_symbol]) {
symbolInUse[_symbol] = true;
symbolCreators[_symbol] = _creator;
symbols.push(_symbol);
}
}
function addModifierCard(
uint256 _cardId,
address _creator,
string calldata _name,
bytes calldata _data
) external onlyAuthorized {
modifierCards[_cardId] = ModifierCard(_creator, 0, _name, _data);
modifierCardNames[_name] = _cardId;
modifiers.push(_cardId);
}
function addCreatorRewardTransaction(
address _creator,
uint256 _modifierCard,
uint256 _symbol,
uint256 _amountIn,
uint256 _amountOut
) external onlyAuthorized {
Reward[] storage rewards = creatorRewards[_creator];
rewards.push(
Reward(
block.timestamp,
_modifierCard,
_symbol,
int256(_amountIn) - int256(_amountOut)
)
);
creatorRewardsBalance[_creator] += _amountIn;
creatorRewardsBalance[_creator] -= _amountOut;
if (knownCreators[_creator] == false) {
knownCreators[_creator] = true;
creators.push(_creator);
}
}
function decrementDeckMintUnlocking() external onlyAuthorized {
if (deckMintUnlocking > 0) {
deckMintUnlocking--;
}
}
function getCard(uint256 _cardId) external view returns (Card memory) {
return cards[_cardId];
}
function getCreators() external view returns (address[] memory) {
return creators;
}
function getCreatorRewards(address _creator)
external
view
onlyAuthorized
returns (Reward[] memory)
{
return creatorRewards[_creator];
}
function getCreatorRewardsBalance(address _creator)
external
view
onlyAuthorized
returns (uint256)
{
return creatorRewardsBalance[_creator];
}
function getDeckCardCount(uint256 _deckId) external view returns (uint256) {
return deckCardCounts[_deckId];
}
function getDeckMintUnlocking()
external
view
onlyAuthorized
returns (uint256)
{
return deckMintUnlocking;
}
function getHandOwner(uint256 _handId) external view returns (address) {
return handOwners[_handId];
}
function getHandCards(uint256 _handId)
external
view
returns (uint256[5] memory)
{
return handCards[_handId];
}
function getModifierCardCreator(uint256 _cardId)
external
view
returns (address)
{
return modifierCards[_cardId].creator;
}
function getModifierCardData(uint256 _cardId)
external
view
returns (bytes memory)
{
return modifierCards[_cardId].data;
}
function getModifierCardIdByName(string calldata _name)
external
view
returns (uint256)
{
return modifierCardNames[_name];
}
function getModifierCardInUse(uint256 _cardId)
external
view
returns (bool)
{
return modifierCards[_cardId].creator != address(0);
}
function getModifierCardName(uint256 _cardId)
external
view
returns (string memory)
{
return modifierCards[_cardId].name;
}
function getModifierCardUsageCount(uint256 _cardId)
external
view
returns (uint256)
{
return modifierCards[_cardId].usageCount;
}
function getModifiers() external view returns (uint256[] memory) {
return modifiers;
}
function getPreshuffledDeck()
external
view
onlyAuthorized
returns (bytes memory)
{
return preShuffledDeck;
}
function getShuffledDeck(uint256 _symbol)
external
view
onlyAuthorized
returns (bytes memory)
{
return shuffledDecks[_symbol];
}
function getSymbolInUse(uint256 _symbol) external view returns (bool) {
return symbolInUse[_symbol];
}
function getSymbolCreator(uint256 _symbol) external view returns (address) {
return symbolCreators[_symbol];
}
function getSymbols() external view returns (uint256[] memory) {
return symbols;
}
function getTotalActiveModifiers() external view returns (uint256) {
uint256 result;
for (uint256 i; i < modifiers.length; i++) {
if (modifierCards[i].usageCount < maxModifierUsage) {
result++;
}
}
return result;
}
function getTotalCards() external view returns (uint256) {
return cards.length;
}
function getTotalModifiers() external view returns (uint256) {
return modifiers.length;
}
function getTotalSymbols() external view returns (uint256) {
return symbols.length;
}
function getTotalRewardsBalance() external view returns (uint256) {
uint256 result;
for (uint256 i; i < creators.length; i++) {
if (creators[i] != address(0)) {
result += creatorRewardsBalance[creators[i]];
}
}
return result;
}
function getUsePermanentStorage(uint256 _tokenId)
external
view
returns (bool)
{
return usePermanentStorage[_tokenId];
}
function incrementModifierCardUsageCount(uint256 _cardId)
external
onlyAuthorized
{
modifierCards[_cardId].usageCount++;
}
function resetDeckMintUnlocking() external onlyAuthorized {
deckMintUnlocking = defaultDeckMintUnlocking;
}
function setDeckMintUnlocking(uint256 _value) external onlyAuthorized {
deckMintUnlocking = _value;
}
function setDefaultDeckMintUnlocking(uint256 _value)
external
onlyAuthorized
{
defaultDeckMintUnlocking = _value;
}
function setBaseURIAndExtension(
string memory _newBaseURI,
string memory _newBaseExtension
) external onlyAuthorized {
baseURI = _newBaseURI;
baseExtension = bytes(_newBaseExtension).length <= 1
? ""
: _newBaseExtension;
}
function setPermanentStorageBaseURIAndExtension(
string memory _newBaseURI,
string memory _newExtension
) external onlyAuthorized {
permanentStorageBaseURI = _newBaseURI;
permanentStorageExtension = bytes(_newExtension).length <= 1
? ""
: _newExtension;
}
function setCard(uint256 _cardId, Card calldata _value)
external
onlyAuthorized
{
cards[_cardId] = _value;
}
function setCosts(
uint256 _cardCost,
uint256 _handCost,
uint256 _deckCost,
uint256 _modifierCost
) external onlyAuthorized {
cardCost = _cardCost;
handCost = _handCost;
deckCost = _deckCost;
modifierCost = _modifierCost;
}
function setHandCards(uint256 _handId, uint256[5] calldata _cards)
external
onlyAuthorized
{
handCards[_handId] = _cards;
}
function setHandOwner(uint256 _handId, address _owner)
external
onlyAuthorized
{
handOwners[_handId] = _owner;
}
function setLimits(
uint32 _maxMintAmount,
uint32 _maxModifierUsage,
uint32 _maxCardsPerDeck,
uint32 _maxSupply
) external onlyAuthorized {
if (_maxMintAmount > 0) maxMintAmount = _maxMintAmount;
if (_maxModifierUsage > 0) maxModifierUsage = _maxModifierUsage;
if (_maxCardsPerDeck > 0) maxCardsPerDeck = _maxCardsPerDeck;
if (_maxSupply > 0) maxSupply = _maxSupply > 65535 ? 65535 : _maxSupply;
}
function setPreshuffledDeck(bytes memory _value) external onlyAuthorized {
preShuffledDeck = _value;
}
function setRewardPercentage(uint32 _value) external onlyAuthorized {
if (_value > 0 && _value <= 100) {
rewardPercentage = _value;
}
}
function setShuffledDeck(uint256 _symbol, bytes memory _value)
external
onlyAuthorized
{
shuffledDecks[_symbol] = _value;
}
function setUsePermanentStorage(uint256 _tokenId, bool _value)
external
onlyAuthorized
{
usePermanentStorage[_tokenId] = _value;
}
}
// SPDX-License-Identifier: None
// Created by 256bit.io - 2021/2022
pragma solidity ^0.8.0;
import "OwnerOrAuthorized.sol";
import "CryptoCardsMessages.sol";
import "CryptoCardsStorage.sol";
struct DecodedCard {
uint256 value;
uint256 suit;
uint256 background;
uint256 foreground;
uint256 color;
uint256 symbol;
uint256 modifierFlags;
}
contract CryptoCardsFactory is OwnerOrAuthorized {
CryptoCardsMessages messages;
CryptoCardsStorage store;
uint256 private psuedoRandomSeed;
uint256[] private CARD_BACKGROUND_COLORS = [
0xff99b433,
0xff00a300,
0xff1e7145,
0xffff0097,
0xff9f00a7,
0xff7e3878,
0xff603cba,
0xff1d1d1d,
0xff00aba9,
0xff2d89ef,
0xff2b5797,
0xffffc40d,
0xffe3a21a,
0xffda532c,
0xffee1111,
0xffb91d47
];
constructor(address _messages, address _storage) OwnerOrAuthorized() {
messages = CryptoCardsMessages(_messages);
store = CryptoCardsStorage(_storage);
}
// Internal
function _encodeCardAttributes(
uint256 _value,
uint256 _suit,
uint256 _background,
uint256 _foreground,
uint256 _color,
uint256 _symbol,
uint256 _modifierFlags
) internal pure returns (uint256) {
return
_value |
(_suit << BITOFFSET_SUIT) |
(_background << BITOFFSET_BACKGROUND) |
(_foreground << BITOFFSET_FOREGROUND) |
(_color << BITOFFSET_COLOR) |
(_symbol << BITOFFSET_SYMBOL) |
(_modifierFlags << BITOFFSET_FLAGS);
}
function _createRandomCard(uint256 _symbol) internal returns (uint256) {
uint256 nextCardIndex = store.getDeckCardCount(_symbol);
bytes memory shuffledCards = store.getShuffledDeck(_symbol);
require(shuffledCards.length > 0, messages.missingShuffledDeck());
// Good enough psuedo-random number; only used for background
unchecked {
psuedoRandomSeed = psuedoRandomSeed == 0
? uint256(blockhash(block.number - 1)) + 1
: psuedoRandomSeed + uint256(blockhash(block.number - 1)) + 1;
}
uint256 randomValue = uint256(
keccak256(
abi.encodePacked(block.timestamp, msg.sender, psuedoRandomSeed)
)
);
uint8 nextCard = uint8(shuffledCards[nextCardIndex % 52]);
uint256 value = nextCard % 13;
uint256 suit = nextCard / 13;
uint256 background = CARD_BACKGROUND_COLORS[randomValue % 16];
return
store.addCard(
createCard(
DecodedCard(
value,
suit,
background,
DEFAULT_FOREGROUND,
DEFAULT_COLOR,
_symbol,
0
),
0
)
);
}
function _modifyCard(uint256 _baseCardId, uint256 _modifierCardId)
internal
{
Card memory baseCard = store.getCard(_baseCardId);
Card memory modifierCard = store.getCard(_modifierCardId);
uint256 value = baseCard.attributes & 0xFF;
uint256 suit = (baseCard.attributes >> BITOFFSET_SUIT) & 0xFF;
uint256 background = (baseCard.attributes >> BITOFFSET_BACKGROUND) &
0xFFFFFFFF;
uint256 foreground = (baseCard.attributes >> BITOFFSET_FOREGROUND) &
0xFFFFFFFF;
uint256 color = (baseCard.attributes >> BITOFFSET_COLOR) & 0xFFFFFFFF;
uint256 symbol = (baseCard.attributes >> BITOFFSET_SYMBOL) & 0xFFFFFFFF;
uint256 modifierFlags = modifierCard.attributes >> BITOFFSET_FLAGS;
// background
if (modifierFlags & FLAGS_SET_BACKGROUND == FLAGS_SET_BACKGROUND) {
background =
(modifierCard.attributes >> BITOFFSET_BACKGROUND) &
0xFFFFFFFF;
}
// foreground
if (modifierFlags & FLAGS_SET_FOREGROUND == FLAGS_SET_FOREGROUND) {
foreground =
(modifierCard.attributes >> BITOFFSET_FOREGROUND) &
0xFFFFFFFF;
}
// color
if (modifierFlags & FLAGS_SET_COLOR == FLAGS_SET_COLOR) {
color = (modifierCard.attributes >> BITOFFSET_COLOR) & 0xFFFFFFFF;
}
// modifiers
if (modifierFlags & FLAGS_DATA_APPEND == FLAGS_DATA_APPEND) {
// append
require(
(baseCard.modifiers & (uint256(0xFFFF) << (32 * 8))) == 0,
messages.modifierDataFull()
);
baseCard.modifiers =
(baseCard.modifiers << 16) |
(_modifierCardId & 0xFFFF);
} else {
// overwrite
baseCard.modifiers = _modifierCardId;
}
baseCard.attributes = _encodeCardAttributes(
value,
suit,
background,
foreground,
color,
symbol,
modifierFlags
);
store.setCard(_baseCardId, baseCard);
store.incrementModifierCardUsageCount(_modifierCardId);
}
// Public
function createCard(DecodedCard memory _cardValues, uint256 _data)
public
onlyAuthorized
returns (Card memory)
{
return
Card(
_encodeCardAttributes(
_cardValues.value,
_cardValues.suit,
_cardValues.background,
_cardValues.foreground,
_cardValues.color,
_cardValues.symbol,
_cardValues.modifierFlags
),
_data
);
}
function createCards(
uint256 _count,
uint256 _symbol,
uint256 _modifierCardId
) external onlyAuthorized returns (uint256[] memory) {
uint256 supply = store.getTotalCards();
uint256 deckSupply = store.getDeckCardCount(_symbol);
require(_count > 0, messages.mintAmount());
require(_count <= store.maxMintAmount(), messages.mintAmount());
require(supply + _count <= store.maxSupply(), messages.exceedsSupply());
require(
deckSupply + _count <= store.maxCardsPerDeck(),
messages.exceedsSupply()
);
if (_modifierCardId > 0) {
require(
store.getModifierCardUsageCount(_modifierCardId) + _count <
store.maxModifierUsage(),
messages.modifierUsage()
);
require(
store.getModifierCardInUse(_modifierCardId) == true,
messages.modifierNotFound()
);
}
uint256[] memory result = new uint256[](_count);
for (uint256 i = 0; i < _count; i++) {
result[i] = _createRandomCard(_symbol);
if (_modifierCardId > 0) {
_modifyCard(result[i], _modifierCardId);
}
}
return result;
}
// Create an array of 52 values and shuffle
function createDeck(uint256 _symbol) external onlyAuthorized {
bytes memory a = store.getPreshuffledDeck();
unchecked {
psuedoRandomSeed = psuedoRandomSeed == 0
? uint256(blockhash(block.number - 1)) + 1
: psuedoRandomSeed + uint256(blockhash(block.number - 1)) + 1;
}
// Shuffle
for (uint256 sourceIndex; sourceIndex < 52; sourceIndex++) {
uint256 destIndex = sourceIndex +
(uint256(
keccak256(
abi.encodePacked(
block.timestamp,
msg.sender,
psuedoRandomSeed
)
)
) % (52 - sourceIndex));
bytes1 temp = a[destIndex];
a[destIndex] = a[sourceIndex];
a[sourceIndex] = temp;
}
store.setShuffledDeck(_symbol, a);
}
function createModifiedCard(
uint256 _originalCardId,
uint256 _modifierCardId
) external onlyAuthorized returns (uint256) {
uint256 supply = store.getTotalCards();
require(supply + 1 <= store.maxSupply(), messages.exceedsSupply());
if (_modifierCardId > 0) {
require(
store.getModifierCardUsageCount(_modifierCardId) <
store.maxModifierUsage(),
messages.modifierUsage()
);
require(
store.getModifierCardInUse(_modifierCardId) == true,
messages.modifierNotFound()
);
}
Card memory originalCard = store.getCard(_originalCardId);
uint256 clonedCardId = store.addCard(
Card(originalCard.attributes, originalCard.modifiers)
);
_modifyCard(clonedCardId, _modifierCardId);
return clonedCardId;
}
function createModifierCard(
uint256 _value,
uint256 _background,
uint256 _foreground,
uint256 _color,
uint256 _flags
) external onlyAuthorized returns (uint256) {
require(
store.getTotalCards() + 1 <= store.maxSupply(),
messages.exceedsSupply()
);
Card memory card = createCard(
DecodedCard(
_value | MODIFIER_CARD,
0,
(_flags & FLAGS_SET_BACKGROUND) == FLAGS_SET_BACKGROUND
? _background
: DEFAULT_MODIFIER_BACKGROUND,
(_flags & FLAGS_SET_FOREGROUND) == FLAGS_SET_FOREGROUND
? _foreground
: DEFAULT_FOREGROUND,
(_flags & FLAGS_SET_COLOR) == FLAGS_SET_COLOR
? _color
: DEFAULT_COLOR,
0,
_flags
),
0
);
return store.addCard(card);
}
}
|
background foreground color modifiers append overwrite
|
function _modifyCard(uint256 _baseCardId, uint256 _modifierCardId)
internal
{
Card memory baseCard = store.getCard(_baseCardId);
Card memory modifierCard = store.getCard(_modifierCardId);
uint256 value = baseCard.attributes & 0xFF;
uint256 suit = (baseCard.attributes >> BITOFFSET_SUIT) & 0xFF;
uint256 background = (baseCard.attributes >> BITOFFSET_BACKGROUND) &
0xFFFFFFFF;
uint256 foreground = (baseCard.attributes >> BITOFFSET_FOREGROUND) &
0xFFFFFFFF;
uint256 color = (baseCard.attributes >> BITOFFSET_COLOR) & 0xFFFFFFFF;
uint256 symbol = (baseCard.attributes >> BITOFFSET_SYMBOL) & 0xFFFFFFFF;
uint256 modifierFlags = modifierCard.attributes >> BITOFFSET_FLAGS;
if (modifierFlags & FLAGS_SET_BACKGROUND == FLAGS_SET_BACKGROUND) {
background =
(modifierCard.attributes >> BITOFFSET_BACKGROUND) &
0xFFFFFFFF;
}
if (modifierFlags & FLAGS_SET_FOREGROUND == FLAGS_SET_FOREGROUND) {
foreground =
(modifierCard.attributes >> BITOFFSET_FOREGROUND) &
0xFFFFFFFF;
}
if (modifierFlags & FLAGS_SET_COLOR == FLAGS_SET_COLOR) {
color = (modifierCard.attributes >> BITOFFSET_COLOR) & 0xFFFFFFFF;
}
if (modifierFlags & FLAGS_DATA_APPEND == FLAGS_DATA_APPEND) {
require(
(baseCard.modifiers & (uint256(0xFFFF) << (32 * 8))) == 0,
messages.modifierDataFull()
);
baseCard.modifiers =
(baseCard.modifiers << 16) |
(_modifierCardId & 0xFFFF);
baseCard.modifiers = _modifierCardId;
}
baseCard.attributes = _encodeCardAttributes(
value,
suit,
background,
foreground,
color,
symbol,
modifierFlags
);
store.setCard(_baseCardId, baseCard);
store.incrementModifierCardUsageCount(_modifierCardId);
}
| 28,051
|
./full_match/80001/0x7CC5EABf47ee0D0baE9dAe15A31f40e867e85804/sources/home/talha-amin/Certoshi/contracts/Certification.sol
|
require(certificates[byte_id].creation_date != 0, "Certificate id does not exist!");
|
function getData(string memory _id) public view returns(string memory, string memory, string memory, string memory, string memory, string memory, bool) {
bytes32 byte_id = stringToBytes32(_id);
Certificate memory temp = certificates[byte_id];
bytes memory tempEmptyStringNameTest = bytes(
certificates[byte_id].creation_date
);
require(
tempEmptyStringNameTest.length != 0,
"Certificate id does not exist"
);
return (temp.candidate_name, temp.course_name, temp.creation_date, temp.institute_name, temp.institute_acronym, temp.institute_link, temp.revoked);
}
| 5,638,909
|
pragma solidity =0.6.2;
pragma experimental ABIEncoderV2;
import '@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol';
import '@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol';
abstract contract IFreeFromUpTo is IERC20 {
function freeFromUpTo(address from, uint256 value) external virtual returns(uint256 freed);
}
interface IDistributeNFTRewards {
function addFeeAndUpdatePrice(uint256 _feeIn) external;
}
contract NFTManager is Initializable, OwnableUpgradeSafe, ERC721UpgradeSafe {
using SafeMath for uint256;
// Time staked in blocks
mapping (address => uint256) public timeStaked;
mapping (address => uint256) public amountStaked;
// TokenURI => blueprint
// the array is a Blueprint with 3 elements. We use this method instead of a struct since structs are not upgradeable
// [0] uint256 mintMax;
// [1] uint256 currentMint; // How many tokens of this type have been minted already
// [2] uint256 yeldCost;
mapping (string => uint256[4]) public blueprints;
mapping (string => bool) public blueprintExists;
// Token ID -> tokenURI without baseURI
mapping (uint256 => string) public myTokenURI;
string[] public tokenURIs;
uint256[] public mintedTokenIds;
uint256 public lastId;
address public yeld;
uint256 public oneDayInBlocks;
address public devTreasury;
uint256 public treasuryPercentage;
uint256 public distributionToOthersPercentage;
address public chi;
address public distributeNFTRewards;
modifier discountCHI {
uint256 gasStart = gasleft();
_;
uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length;
IFreeFromUpTo(chi).freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947);
}
// Chi mainnet 0x0000000000004946c0e9F43F4Dee607b0eF1fA1c
// Base URI has to be like this: https://mynftpage.com/nft-token/
function initialize(address _yeld, address _devTreasury, address _chi, string memory baseUri_) public initializer {
__Ownable_init();
__ERC721_init('NFTManager', 'YELDNFT');
_setBaseURI(baseUri_);
yeld = _yeld;
chi = _chi;
devTreasury = _devTreasury;
treasuryPercentage = 10e18;
distributionToOthersPercentage = 40e18;
oneDayInBlocks = 6500;
}
function setCHI(address _chi) external onlyOwner {
chi = _chi;
}
function setYELD(address _yeld) external onlyOwner {
yeld = _yeld;
}
function setDevTreasury(address _devTreasury) external onlyOwner {
devTreasury = _devTreasury;
}
function setDistributeNFTRewards(address _distributeNFTRewards) external onlyOwner {
distributeNFTRewards = _distributeNFTRewards;
}
function setBaseURI(string calldata baseURI_) external onlyOwner {
_setBaseURI(baseURI_);
}
// Allows the owner to create a blueprint which is how many card can be minted for a particular tokenURI
// NOTE: Remember to deploy the json file to the right URI with the baseURI
function createBlueprint(string memory _tokenURI, uint256 _maxMint, uint256 _yeldCost) public onlyOwner {
uint256[3] memory blueprint = [_maxMint, 0, _yeldCost];
blueprints[_tokenURI] = blueprint;
blueprintExists[_tokenURI] = true;
tokenURIs.push(_tokenURI);
}
function discountSafeMint(string memory _tokenURI) public discountCHI {
safeMint(_tokenURI);
}
function safeMintMultiple(string memory _tokenURI, uint256 _amount) public {
for (uint256 i = 0; i < _amount; i++) {
safeMint(_tokenURI);
}
}
// Mint a card for the sender
// NOTE: remember that the tokenURI most not have the baseURI. For instance:
// - BaseURI is https://examplenft.com/
// - TokenURI must be "token-1" or whatever without the BaseURI
// To create the resulting https://exampleNFT.com/token-1
function safeMint(string memory _tokenURI) public {
// Check that this tokenURI exists
require(blueprintExists[_tokenURI], "NFTManager: That token URI doesn't exist");
// Require than the amount of tokens to mint is not exceeded
require(blueprints[_tokenURI][0] > blueprints[_tokenURI][1], 'NFTManager: The total amount of tokens for this URI have been minted already');
uint256 allowanceYELD = IERC20(yeld).allowance(msg.sender, address(this));
require(allowanceYELD >= blueprints[_tokenURI][2], 'NFTManager: You have to approve the required token amount of YELD to stake');
// Remember that the actual value locked is 50%
uint256 cost = blueprints[_tokenURI][2];
uint256 dev = blueprints[_tokenURI][2].mul(treasuryPercentage).div(1e20);
uint256 distributionToOthers = blueprints[_tokenURI][2].mul(distributionToOthersPercentage).div(1e20);
// Payment
IERC20(yeld).transferFrom(msg.sender, address(this), cost.sub(dev).sub(distributionToOthers));
IERC20(yeld).transferFrom(msg.sender, devTreasury, dev);
IERC20(yeld).transferFrom(msg.sender, distributeNFTRewards, distributionToOthers);
IDistributeNFTRewards(distributeNFTRewards).addFeeAndUpdatePrice(distributionToOthers);
blueprints[_tokenURI][1] = blueprints[_tokenURI][1].add(1);
lastId = lastId.add(1);
mintedTokenIds.push(lastId);
myTokenURI[lastId] = _tokenURI;
// The token URI determines which NFT this is
_safeMint(msg.sender, lastId, "");
_setTokenURI(lastId, _tokenURI);
}
function extractTokensIfStuck(address _token, uint256 _amount) public onlyOwner {
IERC20(_token).transfer(owner(), _amount);
}
function extractETHIfStruck() public onlyOwner {
payable(address(owner())).transfer(address(this).balance);
}
/// @notice this is the reason we need abiencoder v2 to return the string memory
function getTokenURIs() public view returns (string[] memory) {
return tokenURIs;
}
function getBlueprint(string memory _tokenURI) public view returns(uint256[4] memory) {
return blueprints[_tokenURI];
}
}
|
Mint a card for the sender NOTE: remember that the tokenURI most not have the baseURI. For instance: - BaseURI is https:examplenft.com/ - TokenURI must be "token-1" or whatever without the BaseURI To create the resulting https:exampleNFT.com/token-1 Check that this tokenURI exists Require than the amount of tokens to mint is not exceeded Remember that the actual value locked is 50% Payment The token URI determines which NFT this is
|
function safeMint(string memory _tokenURI) public {
require(blueprintExists[_tokenURI], "NFTManager: That token URI doesn't exist");
require(blueprints[_tokenURI][0] > blueprints[_tokenURI][1], 'NFTManager: The total amount of tokens for this URI have been minted already');
uint256 allowanceYELD = IERC20(yeld).allowance(msg.sender, address(this));
require(allowanceYELD >= blueprints[_tokenURI][2], 'NFTManager: You have to approve the required token amount of YELD to stake');
uint256 cost = blueprints[_tokenURI][2];
uint256 dev = blueprints[_tokenURI][2].mul(treasuryPercentage).div(1e20);
uint256 distributionToOthers = blueprints[_tokenURI][2].mul(distributionToOthersPercentage).div(1e20);
IERC20(yeld).transferFrom(msg.sender, address(this), cost.sub(dev).sub(distributionToOthers));
IERC20(yeld).transferFrom(msg.sender, devTreasury, dev);
IERC20(yeld).transferFrom(msg.sender, distributeNFTRewards, distributionToOthers);
IDistributeNFTRewards(distributeNFTRewards).addFeeAndUpdatePrice(distributionToOthers);
blueprints[_tokenURI][1] = blueprints[_tokenURI][1].add(1);
lastId = lastId.add(1);
mintedTokenIds.push(lastId);
myTokenURI[lastId] = _tokenURI;
_safeMint(msg.sender, lastId, "");
_setTokenURI(lastId, _tokenURI);
}
| 14,086,598
|
./full_match/1/0x023Cb563593da062848dD3460C0B72203d3e24a5/sources/src/ClaimManager.sol
|
Manually adjust nextTokenId for a specific ERC721 contract
|
function adjustNextTokenId(
address erc721ContractAddr,
uint256 newTokenId
) external onlyRolesOrOwner(ADMIN_ROLE) {
nextTokenId[erc721ContractAddr] = newTokenId;
}
| 8,485,117
|
/**
*Submitted for verification at Etherscan.io on 2021-06-25
*/
// 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);
}
// File contracts/@openzeppelin/contracts/utils/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File contracts/@openzeppelin/contracts/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/@openzeppelin/contracts/utils/Initializable.sol
// solhint-disable-next-line compiler-version
/**
* @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 || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File contracts/@openzeppelin/contracts/utils/ContextUpgradeable.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File contracts/@openzeppelin/contracts/utils/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 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.
*/
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 contracts/@openzeppelin/contracts/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 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/@openzeppelin/contracts/IERC20Metadata.sol
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
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 contracts/@openzeppelin/contracts/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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File contracts/@openzeppelin/contracts/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 guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overloaded;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File contracts/CosmosToken.sol
contract CosmosERC20 is ERC20 {
uint256 MAX_UINT = 2**256 - 1;
uint8 immutable private _decimals;
constructor(
address peggyAddress_,
string memory name_,
string memory symbol_,
uint8 decimals_
) ERC20(name_, symbol_) {
_decimals = decimals_;
_mint(peggyAddress_, MAX_UINT);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
}
// File contracts/@openzeppelin/contracts/OwnableUpgradeableWithExpiry.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 OwnableUpgradeableWithExpiry is Initializable, ContextUpgradeable {
address private _owner;
uint256 private _deployTimestamp;
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;
_deployTimestamp = block.timestamp;
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() external virtual onlyOwner {
_renounceOwnership();
}
/**
* @dev Get the timestamp of ownership expiry.
* @return The timestamp of ownership expiry.
*/
function getOwnershipExpiryTimestamp() public view returns (uint256) {
return _deployTimestamp + 52 weeks;
}
/**
* @dev Check if the contract ownership is expired.
* @return True if the contract ownership is expired.
*/
function isOwnershipExpired() public view returns (bool) {
return block.timestamp > getOwnershipExpiryTimestamp();
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called after ownership is expired.
*/
function renounceOwnershipAfterExpiry() external {
require(isOwnershipExpired(), "Ownership not yet expired");
_renounceOwnership();
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
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 _renounceOwnership() private {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
uint256[49] private __gap;
}
// File contracts/Peggy.sol
// This is used purely to avoid stack too deep errors
// represents everything about a given validator set
struct ValsetArgs {
// the validators in this set, represented by an Ethereum address
address[] validators;
// the powers of the given validators in the same order as above
uint256[] powers;
// the nonce of this validator set
uint256 valsetNonce;
// the reward amount denominated in the below reward token, can be
// set to zero
uint256 rewardAmount;
// the reward token, should be set to the zero address if not being used
address rewardToken;
}
// Don't change the order of state for working upgrades.
// AND BE AWARE OF INHERITANCE VARIABLES!
// Inherited contracts contain storage slots and must be accounted for in any upgrades
// always test an exact upgrade on testnet and localhost before mainnet upgrades.
contract Peggy is Initializable, OwnableUpgradeableWithExpiry, Pausable, ReentrancyGuard {
using SafeERC20 for IERC20;
// These are updated often
bytes32 public state_lastValsetCheckpoint;
mapping(address => uint256) public state_lastBatchNonces;
mapping(bytes32 => uint256) public state_invalidationMapping;
uint256 public state_lastValsetNonce = 0;
uint256 public state_lastEventNonce = 0;
// These are set once at initialization
bytes32 public state_peggyId;
uint256 public state_powerThreshold;
// TransactionBatchExecutedEvent and SendToCosmosEvent both include the field _eventNonce.
// This is incremented every time one of these events is emitted. It is checked by the
// Cosmos module to ensure that all events are received in order, and that none are lost.
//
// ValsetUpdatedEvent does not include the field _eventNonce because it is never submitted to the Cosmos
// module. It is purely for the use of relayers to allow them to successfully submit batches.
event TransactionBatchExecutedEvent(
uint256 indexed _batchNonce,
address indexed _token,
uint256 _eventNonce
);
event SendToCosmosEvent(
address indexed _tokenContract,
address indexed _sender,
bytes32 indexed _destination,
uint256 _amount,
uint256 _eventNonce
);
event ERC20DeployedEvent(
// TODO(xlab): _cosmosDenom can be represented as bytes32 to allow indexing
string _cosmosDenom,
address indexed _tokenContract,
string _name,
string _symbol,
uint8 _decimals,
uint256 _eventNonce
);
event ValsetUpdatedEvent(
uint256 indexed _newValsetNonce,
uint256 _eventNonce,
uint256 _rewardAmount,
address _rewardToken,
address[] _validators,
uint256[] _powers
);
function initialize(
// A unique identifier for this peggy instance to use in signatures
bytes32 _peggyId,
// How much voting power is needed to approve operations
uint256 _powerThreshold,
// The validator set, not in valset args format since many of it's
// arguments would never be used in this case
address[] calldata _validators,
uint256[] memory _powers
) external initializer {
__Context_init_unchained();
__Ownable_init_unchained();
// CHECKS
// Check that validators, powers, and signatures (v,r,s) set is well-formed
require(
_validators.length == _powers.length,
"Malformed current validator set"
);
// Check cumulative power to ensure the contract has sufficient power to actually
// pass a vote
uint256 cumulativePower = 0;
for (uint256 i = 0; i < _powers.length; i++) {
cumulativePower = cumulativePower + _powers[i];
if (cumulativePower > _powerThreshold) {
break;
}
}
require(
cumulativePower > _powerThreshold,
"Submitted validator set signatures do not have enough power."
);
ValsetArgs memory _valset;
_valset = ValsetArgs(_validators, _powers, 0, 0, address(0));
bytes32 newCheckpoint = makeCheckpoint(_valset, _peggyId);
// ACTIONS
state_peggyId = _peggyId;
state_powerThreshold = _powerThreshold;
state_lastValsetCheckpoint = newCheckpoint;
state_lastEventNonce = state_lastEventNonce + 1;
// LOGS
emit ValsetUpdatedEvent(
state_lastValsetNonce,
state_lastEventNonce,
0,
address(0),
_validators,
_powers
);
}
function lastBatchNonce(address _erc20Address) public view returns (uint256) {
return state_lastBatchNonces[_erc20Address];
}
// Utility function to verify geth style signatures
function verifySig(
address _signer,
bytes32 _theHash,
uint8 _v,
bytes32 _r,
bytes32 _s
) private pure returns (bool) {
bytes32 messageDigest =
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _theHash));
return _signer == ecrecover(messageDigest, _v, _r, _s);
}
// Make a new checkpoint from the supplied validator set
// A checkpoint is a hash of all relevant information about the valset. This is stored by the contract,
// instead of storing the information directly. This saves on storage and gas.
// The format of the checkpoint is:
// h(peggyId, "checkpoint", valsetNonce, validators[], powers[])
// Where h is the keccak256 hash function.
// The validator powers must be decreasing or equal. This is important for checking the signatures on the
// next valset, since it allows the caller to stop verifying signatures once a quorum of signatures have been verified.
function makeCheckpoint(ValsetArgs memory _valsetArgs, bytes32 _peggyId)
private
pure
returns (bytes32)
{
// bytes32 encoding of the string "checkpoint"
bytes32 methodName =
0x636865636b706f696e7400000000000000000000000000000000000000000000;
bytes32 checkpoint =
keccak256(
abi.encode(
_peggyId,
methodName,
_valsetArgs.valsetNonce,
_valsetArgs.validators,
_valsetArgs.powers,
_valsetArgs.rewardAmount,
_valsetArgs.rewardToken
)
);
return checkpoint;
}
function checkValidatorSignatures(
// The current validator set and their powers
address[] memory _currentValidators,
uint256[] memory _currentPowers,
// The current validator's signatures
uint8[] memory _v,
bytes32[] memory _r,
bytes32[] memory _s,
// This is what we are checking they have signed
bytes32 _theHash,
uint256 _powerThreshold
) private pure {
uint256 cumulativePower = 0;
for (uint256 i = 0; i < _currentValidators.length; i++) {
// If v is set to 0, this signifies that it was not possible to get a signature from this validator and we skip evaluation
// (In a valid signature, it is either 27 or 28)
if (_v[i] != 0) {
// Check that the current validator has signed off on the hash
require(
verifySig(_currentValidators[i], _theHash, _v[i], _r[i], _s[i]),
"Validator signature does not match."
);
// Sum up cumulative power
cumulativePower = cumulativePower + _currentPowers[i];
// Break early to avoid wasting gas
if (cumulativePower > _powerThreshold) {
break;
}
}
}
// Check that there was enough power
require(
cumulativePower > _powerThreshold,
"Submitted validator set signatures do not have enough power."
);
// Success
}
// This updates the valset by checking that the validators in the current valset have signed off on the
// new valset. The signatures supplied are the signatures of the current valset over the checkpoint hash
// generated from the new valset.
// Anyone can call this function, but they must supply valid signatures of state_powerThreshold of the current valset over
// the new valset.
function updateValset(
// The new version of the validator set
ValsetArgs memory _newValset,
// The current validators that approve the change
ValsetArgs memory _currentValset,
// These are arrays of the parts of the current validator's signatures
uint8[] memory _v,
bytes32[] memory _r,
bytes32[] memory _s
) external whenNotPaused {
// CHECKS
// Check that the valset nonce is greater than the old one
require(
_newValset.valsetNonce > _currentValset.valsetNonce,
"New valset nonce must be greater than the current nonce"
);
// Check that new validators and powers set is well-formed
require(
_newValset.validators.length == _newValset.powers.length,
"Malformed new validator set"
);
// Check that current validators, powers, and signatures (v,r,s) set is well-formed
require(
_currentValset.validators.length == _currentValset.powers.length &&
_currentValset.validators.length == _v.length &&
_currentValset.validators.length == _r.length &&
_currentValset.validators.length == _s.length,
"Malformed current validator set"
);
// Check that the supplied current validator set matches the saved checkpoint
require(
makeCheckpoint(_currentValset, state_peggyId) ==
state_lastValsetCheckpoint,
"Supplied current validators and powers do not match checkpoint."
);
// Check that enough current validators have signed off on the new validator set
bytes32 newCheckpoint = makeCheckpoint(_newValset, state_peggyId);
checkValidatorSignatures(
_currentValset.validators,
_currentValset.powers,
_v,
_r,
_s,
newCheckpoint,
state_powerThreshold
);
// ACTIONS
// Stored to be used next time to validate that the valset
// supplied by the caller is correct.
state_lastValsetCheckpoint = newCheckpoint;
// Store new nonce
state_lastValsetNonce = _newValset.valsetNonce;
// Send submission reward to msg.sender if reward token is a valid value
if (_newValset.rewardToken != address(0) && _newValset.rewardAmount != 0) {
IERC20(_newValset.rewardToken).safeTransfer(
msg.sender,
_newValset.rewardAmount
);
}
// LOGS
state_lastEventNonce = state_lastEventNonce + 1;
emit ValsetUpdatedEvent(
_newValset.valsetNonce,
state_lastEventNonce,
_newValset.rewardAmount,
_newValset.rewardToken,
_newValset.validators,
_newValset.powers
);
}
// submitBatch processes a batch of Cosmos -> Ethereum transactions by sending the tokens in the transactions
// to the destination addresses. It is approved by the current Cosmos validator set.
// Anyone can call this function, but they must supply valid signatures of state_powerThreshold of the current valset over
// the batch.
function submitBatch(
// The validators that approve the batch
ValsetArgs memory _currentValset,
// These are arrays of the parts of the validators signatures
uint8[] memory _v,
bytes32[] memory _r,
bytes32[] memory _s,
// The batch of transactions
uint256[] memory _amounts,
address[] memory _destinations,
uint256[] memory _fees,
uint256 _batchNonce,
address _tokenContract,
// a block height beyond which this batch is not valid
// used to provide a fee-free timeout
uint256 _batchTimeout
) external nonReentrant whenNotPaused {
// CHECKS scoped to reduce stack depth
{
// Check that the batch nonce is higher than the last nonce for this token
require(
state_lastBatchNonces[_tokenContract] < _batchNonce,
"New batch nonce must be greater than the current nonce"
);
// Check that the block height is less than the timeout height
require(
block.number < _batchTimeout,
"Batch timeout must be greater than the current block height"
);
// Check that current validators, powers, and signatures (v,r,s) set is well-formed
require(
_currentValset.validators.length == _currentValset.powers.length &&
_currentValset.validators.length == _v.length &&
_currentValset.validators.length == _r.length &&
_currentValset.validators.length == _s.length,
"Malformed current validator set"
);
// Check that the supplied current validator set matches the saved checkpoint
require(
makeCheckpoint(_currentValset, state_peggyId) ==
state_lastValsetCheckpoint,
"Supplied current validators and powers do not match checkpoint."
);
// Check that the transaction batch is well-formed
require(
_amounts.length == _destinations.length &&
_amounts.length == _fees.length,
"Malformed batch of transactions"
);
// Check that enough current validators have signed off on the transaction batch and valset
checkValidatorSignatures(
_currentValset.validators,
_currentValset.powers,
_v,
_r,
_s,
// Get hash of the transaction batch and checkpoint
keccak256(
abi.encode(
state_peggyId,
// bytes32 encoding of "transactionBatch"
0x7472616e73616374696f6e426174636800000000000000000000000000000000,
_amounts,
_destinations,
_fees,
_batchNonce,
_tokenContract,
_batchTimeout
)
),
state_powerThreshold
);
// ACTIONS
// Store batch nonce
state_lastBatchNonces[_tokenContract] = _batchNonce;
{
// Send transaction amounts to destinations
uint256 totalFee;
for (uint256 i = 0; i < _amounts.length; i++) {
IERC20(_tokenContract).safeTransfer(_destinations[i], _amounts[i]);
totalFee = totalFee + _fees[i];
}
if (totalFee > 0) {
// Send transaction fees to msg.sender
IERC20(_tokenContract).safeTransfer(msg.sender, totalFee);
}
}
}
// LOGS scoped to reduce stack depth
{
state_lastEventNonce = state_lastEventNonce + 1;
emit TransactionBatchExecutedEvent(
_batchNonce,
_tokenContract,
state_lastEventNonce
);
}
}
function sendToCosmos(
address _tokenContract,
bytes32 _destination,
uint256 _amount
) external whenNotPaused nonReentrant {
IERC20(_tokenContract).safeTransferFrom(msg.sender, address(this), _amount);
state_lastEventNonce = state_lastEventNonce + 1;
emit SendToCosmosEvent(
_tokenContract,
msg.sender,
_destination,
_amount,
state_lastEventNonce
);
}
function deployERC20(
string calldata _cosmosDenom,
string calldata _name,
string calldata _symbol,
uint8 _decimals
) external {
// Deploy an ERC20 with entire supply granted to Peggy.sol
CosmosERC20 erc20 =
new CosmosERC20(address(this), _name, _symbol, _decimals);
// Fire an event to let the Cosmos module know
state_lastEventNonce = state_lastEventNonce + 1;
emit ERC20DeployedEvent(
_cosmosDenom,
address(erc20),
_name,
_symbol,
_decimals,
state_lastEventNonce
);
}
function emergencyPause() external onlyOwner {
_pause();
}
function emergencyUnpause() external onlyOwner {
_unpause();
}
}
|
Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called after ownership is expired./
|
function renounceOwnershipAfterExpiry() external {
require(isOwnershipExpired(), "Ownership not yet expired");
_renounceOwnership();
}
| 2,134,334
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.