contract_name
stringlengths 1
61
| file_path
stringlengths 5
50.4k
| contract_address
stringlengths 42
42
| language
stringclasses 1
value | class_name
stringlengths 1
61
| class_code
stringlengths 4
330k
| class_documentation
stringlengths 0
29.1k
| class_documentation_type
stringclasses 6
values | func_name
stringlengths 0
62
| func_code
stringlengths 1
303k
| func_documentation
stringlengths 2
14.9k
| func_documentation_type
stringclasses 4
values | compiler_version
stringlengths 15
42
| license_type
stringclasses 14
values | swarm_source
stringlengths 0
71
| meta
dict | __index_level_0__
int64 0
60.4k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DSPXToken
|
DSPXToken.sol
|
0x30dda19c0b94a88ed8784868ec1e9375d9f0e27c
|
Solidity
|
DSPXToken
|
contract DSPXToken is StandardToken {
string public constant name = "SP8DE PreSale Token";
string public constant symbol = "DSPX";
uint8 public constant decimals = 18;
address public preSale;
address public team;
bool public isFrozen = true;
uint public constant TOKEN_LIMIT = 888888888 * (1e18);
// Constructor
function DSPXToken(address _preSale, address _team) {
require(_preSale != address(0));
require(_team != address(0));
preSale = _preSale;
team = _team;
}
// Create tokens
function mint(address holder, uint value) {
require(msg.sender == preSale);
require(value > 0);
require(totalSupply + value <= TOKEN_LIMIT);
balances[holder] += value;
totalSupply += value;
Transfer(0x0, holder, value);
}
// Allow token transfer
function unfreeze() external {
require(msg.sender == team);
isFrozen = false;
}
// ERC20 functions
// =========================
function transfer(address _to, uint _value) public returns (bool) {
require(!isFrozen);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(!isFrozen);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint _value) public returns (bool) {
require(!isFrozen);
return super.approve(_spender, _value);
}
}
|
/**
* @title Spade PreSale Token
*/
|
NatSpecMultiLine
|
mint
|
function mint(address holder, uint value) {
require(msg.sender == preSale);
require(value > 0);
require(totalSupply + value <= TOKEN_LIMIT);
balances[holder] += value;
totalSupply += value;
Transfer(0x0, holder, value);
}
|
// Create tokens
|
LineComment
|
v0.4.19+commit.c4cbbb05
|
bzzr://d961e0a47bc4cf5ebb39e35a59fbf85143aac7b1ab3c863339234c50059d8526
|
{
"func_code_index": [
552,
811
]
}
| 54,961 |
|
DSPXToken
|
DSPXToken.sol
|
0x30dda19c0b94a88ed8784868ec1e9375d9f0e27c
|
Solidity
|
DSPXToken
|
contract DSPXToken is StandardToken {
string public constant name = "SP8DE PreSale Token";
string public constant symbol = "DSPX";
uint8 public constant decimals = 18;
address public preSale;
address public team;
bool public isFrozen = true;
uint public constant TOKEN_LIMIT = 888888888 * (1e18);
// Constructor
function DSPXToken(address _preSale, address _team) {
require(_preSale != address(0));
require(_team != address(0));
preSale = _preSale;
team = _team;
}
// Create tokens
function mint(address holder, uint value) {
require(msg.sender == preSale);
require(value > 0);
require(totalSupply + value <= TOKEN_LIMIT);
balances[holder] += value;
totalSupply += value;
Transfer(0x0, holder, value);
}
// Allow token transfer
function unfreeze() external {
require(msg.sender == team);
isFrozen = false;
}
// ERC20 functions
// =========================
function transfer(address _to, uint _value) public returns (bool) {
require(!isFrozen);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(!isFrozen);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint _value) public returns (bool) {
require(!isFrozen);
return super.approve(_spender, _value);
}
}
|
/**
* @title Spade PreSale Token
*/
|
NatSpecMultiLine
|
unfreeze
|
function unfreeze() external {
require(msg.sender == team);
isFrozen = false;
}
|
// Allow token transfer
|
LineComment
|
v0.4.19+commit.c4cbbb05
|
bzzr://d961e0a47bc4cf5ebb39e35a59fbf85143aac7b1ab3c863339234c50059d8526
|
{
"func_code_index": [
841,
940
]
}
| 54,962 |
|
DSPXToken
|
DSPXToken.sol
|
0x30dda19c0b94a88ed8784868ec1e9375d9f0e27c
|
Solidity
|
DSPXToken
|
contract DSPXToken is StandardToken {
string public constant name = "SP8DE PreSale Token";
string public constant symbol = "DSPX";
uint8 public constant decimals = 18;
address public preSale;
address public team;
bool public isFrozen = true;
uint public constant TOKEN_LIMIT = 888888888 * (1e18);
// Constructor
function DSPXToken(address _preSale, address _team) {
require(_preSale != address(0));
require(_team != address(0));
preSale = _preSale;
team = _team;
}
// Create tokens
function mint(address holder, uint value) {
require(msg.sender == preSale);
require(value > 0);
require(totalSupply + value <= TOKEN_LIMIT);
balances[holder] += value;
totalSupply += value;
Transfer(0x0, holder, value);
}
// Allow token transfer
function unfreeze() external {
require(msg.sender == team);
isFrozen = false;
}
// ERC20 functions
// =========================
function transfer(address _to, uint _value) public returns (bool) {
require(!isFrozen);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(!isFrozen);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint _value) public returns (bool) {
require(!isFrozen);
return super.approve(_spender, _value);
}
}
|
/**
* @title Spade PreSale Token
*/
|
NatSpecMultiLine
|
transfer
|
function transfer(address _to, uint _value) public returns (bool) {
require(!isFrozen);
return super.transfer(_to, _value);
}
|
// ERC20 functions
// =========================
|
LineComment
|
v0.4.19+commit.c4cbbb05
|
bzzr://d961e0a47bc4cf5ebb39e35a59fbf85143aac7b1ab3c863339234c50059d8526
|
{
"func_code_index": [
997,
1142
]
}
| 54,963 |
|
NFIWETHPool
|
@openzeppelin/contracts/token/ERC20/SafeERC20.sol
|
0x2e0c79399d3188b0860ef75925bc910802c33c72
|
Solidity
|
SafeERC20
|
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
|
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
|
NatSpecMultiLine
|
callOptionalReturn
|
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
|
/**
* @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).
*/
|
NatSpecMultiLine
|
v0.5.16+commit.9c3226ce
|
None
|
bzzr://11f167d3db10e80bd17d87937f2bb33171fdb36ee5e4beef61453706e37d9434
|
{
"func_code_index": [
2127,
3246
]
}
| 54,964 |
NFIWETHPool
|
@openzeppelin/contracts/token/ERC20/SafeERC20.sol
|
0x2e0c79399d3188b0860ef75925bc910802c33c72
|
Solidity
|
NFIWETHPool
|
contract NFIWETHPool is NFITokenWrapper, IRewardDistributionRecipient {
// !! Mainnet NFI token address
IERC20 public nfi = IERC20(0x2CE41ACEcBb817D7307D6D6b38C643b269F5580E);
uint256 public constant DURATION = 7 days;
// !! Mainnet pool start time: utc+8 2020-11-11 20:00:00
uint256 public constant startTime = 1605096000; //utc+8 2020-11-11 20:00:00
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored = 0;
bool private open = true;
uint256 private constant _gunit = 1e18;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards; // Unclaimed rewards
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event SetOpen(bool _open);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
/**
* Calculate the rewards for each token
*/
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(_gunit)
.div(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(_gunit)
.add(rewards[account]);
}
function stake(uint256 amount) public checkOpen checkStart updateReward(msg.sender){
require(amount > 0, "NFI-WETH-POOL: Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public checkStart updateReward(msg.sender){
require(amount > 0, "NFI-WETH-POOL: Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public checkStart updateReward(msg.sender){
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
nfi.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
modifier checkStart(){
require(block.timestamp > startTime,"NFI-WETH-POOL: Not start");
_;
}
modifier checkOpen() {
require(open, "NFI-WETH-POOL: Pool is closed");
_;
}
function getPeriodFinish() external view returns (uint256) {
return periodFinish;
}
function isOpen() external view returns (bool) {
return open;
}
function setOpen(bool _open) external onlyOwner {
open = _open;
emit SetOpen(_open);
}
function notifyRewardAmount(uint256 reward)
external
onlyRewardDistribution
checkOpen
updateReward(address(0)){
if (block.timestamp > startTime){
if (block.timestamp >= periodFinish) {
uint256 period = block.timestamp.sub(startTime).div(DURATION).add(1);
periodFinish = startTime.add(period.mul(DURATION));
rewardRate = reward.div(periodFinish.sub(block.timestamp));
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(remaining);
}
lastUpdateTime = block.timestamp;
}else {
rewardRate = reward.div(DURATION);
periodFinish = startTime.add(DURATION);
lastUpdateTime = startTime;
}
nfi.mint(address(this),reward);
emit RewardAdded(reward);
// avoid overflow to lock assets
_checkRewardRate();
}
function _checkRewardRate() internal view returns (uint256) {
return DURATION.mul(rewardRate).mul(_gunit);
}
}
|
rewardPerToken
|
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(_gunit)
.div(totalSupply())
);
}
|
/**
* Calculate the rewards for each token
*/
|
NatSpecMultiLine
|
v0.5.16+commit.9c3226ce
|
None
|
bzzr://11f167d3db10e80bd17d87937f2bb33171fdb36ee5e4beef61453706e37d9434
|
{
"func_code_index": [
1540,
1923
]
}
| 54,965 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
createNewSession
|
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
|
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
2991,
4138
]
}
| 54,966 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
setVote
|
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
|
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
4482,
5501
]
}
| 54,967 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
weightVote
|
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
|
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
6698,
8422
]
}
| 54,968 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
setFinalAppraisal
|
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
|
/// @notice takes average of appraisals and outputs a final appraisal value.
|
NatSpecSingleLine
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
8509,
9595
]
}
| 54,969 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
harvest
|
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
|
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
|
NatSpecMultiLine
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
10042,
12543
]
}
| 54,970 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
claim
|
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
|
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
|
NatSpecSingleLine
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
13011,
16180
]
}
| 54,971 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
endSession
|
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
|
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
|
NatSpecSingleLine
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
16339,
16831
]
}
| 54,972 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
_executeEnd
|
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
|
/* ======== INTERNAL FUNCTIONS ======== */
|
Comment
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
16881,
17670
]
}
| 54,973 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
addToBounty
|
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
|
/// @notice allow any user to add additional bounty on session of their choice
|
NatSpecSingleLine
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
17798,
18099
]
}
| 54,974 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
addToAppraisal
|
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
|
/// @notice allow any user to support any user of their choice
|
NatSpecSingleLine
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
18172,
18617
]
}
| 54,975 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
getStatus
|
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
|
/* ======== VIEW FUNCTIONS ======== */
|
Comment
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
18663,
18921
]
}
| 54,976 |
||
BountyAuction
|
contracts/PricingSession.sol
|
0x5165a6cf99f58aa20032abdf5aaf3f8cd6978617
|
Solidity
|
PricingSession
|
contract PricingSession is ReentrancyGuard {
using SafeMath for uint;
address immutable public ABCToken;
address immutable public Treasury;
address auction;
address admin;
bool auctionStatus;
/* ======== MAPPINGS ======== */
mapping(address => mapping (uint => uint)) public nftNonce;
mapping(uint => mapping(address => mapping(uint => VotingSessionMapping))) NftSessionMap;
mapping(uint => mapping(address => mapping(uint => VotingSessionChecks))) public NftSessionCheck;
mapping(uint => mapping(address => mapping(uint => VotingSessionCore))) public NftSessionCore;
mapping(uint => mapping(address => mapping(uint => uint))) public finalAppraisalValue;
/* ======== STRUCTS ======== */
struct VotingSessionMapping {
mapping (address => uint) voterCheck;
mapping (address => uint) winnerPoints;
mapping (address => uint) amountHarvested;
mapping (address => Voter) nftVotes;
}
struct VotingSessionChecks {
uint sessionProgression;
uint calls;
uint correct;
uint incorrect;
uint timeFinalAppraisalSet;
}
struct VotingSessionCore {
address Dao;
uint endTime;
uint lowestStake;
uint maxAppraisal;
uint totalAppraisalValue;
uint totalSessionStake;
uint totalProfit;
uint totalWinnerPoints;
uint totalVotes;
uint uniqueVoters;
uint votingTime;
}
struct Voter {
bytes32 concealedBid;
uint base;
uint appraisal;
uint stake;
}
/* ======== EVENTS ======== */
event PricingSessionCreated(address DaoTokenContract, address creator_, address nftAddress_, uint tokenid_, uint initialAppraisal_, uint bounty_);
event newAppraisalAdded(address voter_, uint stake_, uint appraisal, uint weight);
event finalAppraisalDetermined(uint finalAppraisal, uint amountOfParticipants, uint totalStake);
event lossHarvestedFromUser(address user_, uint harvested);
event ethClaimedByUser(address user_, uint ethClaimed);
event ethToPPExchange(address user_, uint ethExchanged, uint ppSent);
event sessionEnded(address nftAddress, uint tokenid, uint nonce);
/* ======== CONSTRUCTOR ======== */
constructor(address _ABCToken, address _treasury, address _auction) {
ABCToken = _ABCToken;
Treasury = _treasury;
auction = _auction;
admin = msg.sender;
auctionStatus = true;
}
function setAuction(address _auction) external {
require(msg.sender == admin);
auction = _auction;
}
function setAuctionStatus(bool status) external {
auctionStatus = status;
}
/// @notice Allow user to create new session and attach initial bounty
/**
@dev NFT sessions are indexed using a nonce per specific nft.
The mapping is done by mapping a nonce to an NFT address to the
NFT token id.
*/
function createNewSession(
address nftAddress,
uint tokenid,
uint _initialAppraisal,
uint _votingTime,
address _dao
) stopOverwrite(nftAddress, tokenid) external payable {
require(_votingTime <= 1 days && (auctionStatus || msg.sender == auction));
uint abcCost = 0.005 ether *(ethToAbc());
(bool abcSent) = IERC20(ABCToken).transferFrom(msg.sender, Treasury, abcCost);
require(abcSent);
if(getStatus(nftAddress, tokenid) == 6) {
_executeEnd(nftAddress, tokenid);
}
nftNonce[nftAddress][tokenid]++;
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCore.votingTime = _votingTime;
sessionCore.maxAppraisal = 69420 * _initialAppraisal / 1000;
sessionCore.lowestStake = 100000 ether;
sessionCore.endTime = block.timestamp + _votingTime;
sessionCore.totalSessionStake = msg.value;
sessionCore.Dao = _dao;
emit PricingSessionCreated(_dao, msg.sender, nftAddress, tokenid, _initialAppraisal, msg.value);
}
/* ======== USER VOTE FUNCTIONS ======== */
/// @notice Allows user to set vote in party
/**
@dev Users appraisal is hashed so users can't track final appraisal and submit vote right before session ends.
Therefore, users must remember their appraisal in order to reveal their appraisal in the next function.
*/
function setVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) properVote(nftAddress, tokenid) payable external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionMap.voterCheck[msg.sender] = 1;
if (msg.value < sessionCore.lowestStake) {
sessionCore.lowestStake = msg.value;
}
sessionCore.uniqueVoters++;
sessionCore.totalSessionStake = sessionCore.totalSessionStake.add(msg.value);
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
sessionMap.nftVotes[msg.sender].stake = msg.value;
}
function updateVote(
address nftAddress,
uint tokenid,
bytes32 concealedBid
) external {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 1);
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[currentNonce][nftAddress][tokenid];
require(sessionCore.endTime > block.timestamp);
// if(sessionCore.Dao != address(0)) {
// require(IERC20(sessionCore.Dao).balanceOf(msg.sender) > 0);
// }
sessionCore.uniqueVoters++;
sessionMap.nftVotes[msg.sender].concealedBid = concealedBid;
}
/// @notice Reveals user vote and weights based on the sessions lowest stake
/**
@dev calculation can be found in the weightVoteLibrary.sol file.
Votes are weighted as sqrt(userStake/lowestStake). Depending on a votes weight
it is then added as multiple votes of that appraisal (i.e. if someoneone has
voting weight of 8, 8 votes are submitted using their appraisal).
*/
function weightVote(address nftAddress, uint tokenid, uint appraisal, uint seedNum) checkParticipation(nftAddress, tokenid) nonReentrant external {
uint currentNonce = nftNonce[nftAddress][tokenid];
VotingSessionCore storage sessionCore = NftSessionCore[currentNonce][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[currentNonce][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(sessionCheck.sessionProgression < 2
&& sessionCore.endTime < block.timestamp
&& sessionMap.voterCheck[msg.sender] == 1
&& sessionMap.nftVotes[msg.sender].concealedBid == keccak256(abi.encodePacked(appraisal, msg.sender, seedNum))
&& sessionCore.maxAppraisal >= appraisal
);
sessionMap.voterCheck[msg.sender] = 2;
if(sessionCheck.sessionProgression == 0) {
sessionCheck.sessionProgression = 1;
}
sessionMap.nftVotes[msg.sender].appraisal = appraisal;
uint weight = sqrtLibrary.sqrt(sessionMap.nftVotes[msg.sender].stake/sessionCore.lowestStake);
sessionCore.totalVotes += weight;
sessionCheck.calls++;
sessionCore.totalAppraisalValue = sessionCore.totalAppraisalValue.add((weight) * sessionMap.nftVotes[msg.sender].appraisal);
emit newAppraisalAdded(msg.sender, sessionMap.nftVotes[msg.sender].stake, sessionMap.nftVotes[msg.sender].appraisal, weight);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 2;
sessionCheck.calls = 0;
}
}
/// @notice takes average of appraisals and outputs a final appraisal value.
function setFinalAppraisal(address nftAddress, uint tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
(block.timestamp > sessionCore.endTime + sessionCore.votingTime || sessionCheck.sessionProgression == 2)
);
if(sessionCheck.sessionProgression == 1) {
sessionCheck.sessionProgression = 2;
}
IABCTreasury(Treasury).updateNftPriced();
sessionCheck.calls = 0;
sessionCheck.timeFinalAppraisalSet = block.timestamp;
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid] = (sessionCore.totalAppraisalValue)/(sessionCore.totalVotes);
sessionCheck.sessionProgression = 3;
emit finalAppraisalDetermined(finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid], sessionCore.uniqueVoters, sessionCore.totalSessionStake);
}
/// @notice Calculates users base and harvests their loss before returning remaining stake
/**
@dev A couple notes:
1. Base is calculated based on margin of error.
> +/- 5% = 1
> +/- 4% = 2
> +/- 3% = 3
> +/- 2% = 4
> +/- 1% = 5
> Exact = 6
2. winnerPoints are calculated based on --> base * stake
3. Losses are harvested based on --> (margin of error - 5%) * stake
*/
function harvest(address nftAddress, uint tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(
sessionCheck.sessionProgression == 3
);
sessionCheck.calls++;
sessionMap.voterCheck[msg.sender] = 3;
sessionMap.nftVotes[msg.sender].base =
PostSessionLibrary.calculateBase(
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid],
sessionMap.nftVotes[msg.sender].appraisal
);
if(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[msg.sender].base > 0) {
sessionCore.totalWinnerPoints += sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionMap.winnerPoints[msg.sender] = sessionMap.nftVotes[msg.sender].base * sessionMap.nftVotes[msg.sender].stake;
sessionCheck.correct++;
}
else {
sessionCheck.incorrect++;
}
sessionMap.amountHarvested[msg.sender] = PostSessionLibrary.harvest(
sessionMap.nftVotes[msg.sender].stake,
sessionMap.nftVotes[msg.sender].appraisal,
finalAppraisalValue[nftNonce[nftAddress][tokenid]][nftAddress][tokenid]
);
sessionMap.nftVotes[msg.sender].stake -= sessionMap.amountHarvested[msg.sender];
uint commission = PostSessionLibrary.setCommission(Treasury.balance).mul(sessionMap.amountHarvested[msg.sender]).div(10000);
sessionCore.totalSessionStake -= commission;
sessionMap.amountHarvested[msg.sender] -= commission;
sessionCore.totalProfit += sessionMap.amountHarvested[msg.sender];
IABCTreasury(Treasury).updateProfitGenerated(sessionMap.amountHarvested[msg.sender]);
(bool sent, ) = payable(Treasury).call{value: commission}("");
require(sent);
emit lossHarvestedFromUser(msg.sender, sessionMap.amountHarvested[msg.sender]);
if(sessionCheck.calls == sessionCore.uniqueVoters) {
sessionCheck.sessionProgression = 4;
sessionCheck.calls = 0;
}
}
/// @notice User claims principal stake along with any earned profits in ETH or ABC form
/**
@dev
1. Calculates user principal return value
2. Enacts sybil defense mechanism
3. Edits totalProfits and totalSessionStake to reflect claim
4. Checks trigger choice
5. Executes desired payout of principal and profit
*/
/// @param trigger trigger should be set to 1 if the user wants reward in ETH or 2 if user wants reward in ABC
function claim(address nftAddress, uint tokenid, uint trigger) checkHarvestLoss(nftAddress, tokenid) checkParticipation(nftAddress, tokenid) nonReentrant external returns(uint){
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionMapping storage sessionMap = NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require(block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime || sessionCheck.sessionProgression == 4);
require(trigger == 1 || trigger == 2);
uint principalReturn;
sessionMap.voterCheck[msg.sender] = 4;
if(sessionCheck.sessionProgression == 3) {
sessionCheck.calls = 0;
sessionCheck.sessionProgression = 4;
}
if(sessionCheck.correct * 100 / (sessionCheck.correct + sessionCheck.incorrect) >= 90) {
principalReturn = sessionMap.nftVotes[msg.sender].stake + sessionMap.amountHarvested[msg.sender];
}
else {
principalReturn = sessionMap.nftVotes[msg.sender].stake;
}
sessionCheck.calls++;
uint payout = sessionCore.totalProfit * sessionMap.winnerPoints[msg.sender] / sessionCore.totalWinnerPoints;
sessionCore.totalProfit -= payout;
sessionCore.totalSessionStake -= payout + principalReturn;
sessionCore.totalWinnerPoints -= sessionMap.winnerPoints[msg.sender];
sessionMap.winnerPoints[msg.sender] = 0;
if(sessionMap.winnerPoints[msg.sender] == 0) {
trigger = 1;
}
if(trigger == 1) {
(bool sent1, ) = payable(msg.sender).call{value: principalReturn + payout}("");
require(sent1);
emit ethClaimedByUser(msg.sender, payout);
}
else if(trigger == 2) {
uint abcAmount = payout * 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
uint abcPayout = payout/2 * (1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000) + 1e18 / (0.00005 ether + 0.000015 ether * (IABCTreasury(Treasury).tokensClaimed() + abcAmount) / 1000000));
(bool sent2, ) = payable(msg.sender).call{value: principalReturn}("");
require(sent2);
(bool sent3, ) = payable(Treasury).call{value: payout}("");
require(sent3);
IABCTreasury(Treasury).sendABCToken(msg.sender,abcPayout);
emit ethToPPExchange(msg.sender, payout, abcPayout);
}
if(sessionCore.totalWinnerPoints == 0) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
if(sessionCheck.calls == sessionCore.uniqueVoters || block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime*2) {
sessionCheck.sessionProgression = 5;
_executeEnd(nftAddress, tokenid);
return 0;
}
return 1;
}
/// @notice Custodial function to clear funds and remove session as child
/// @dev Caller receives 10% of the funds that are meant to be cleared
function endSession(address nftAddress, uint tokenid) public {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
require((block.timestamp > sessionCheck.timeFinalAppraisalSet + sessionCore.votingTime * 2) || sessionCheck.sessionProgression == 5);
_executeEnd(nftAddress, tokenid);
}
/* ======== INTERNAL FUNCTIONS ======== */
function _executeEnd(address nftAddress, uint tokenid) internal {
VotingSessionCore storage sessionCore = NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
sessionCheck.sessionProgression = 6;
uint tPayout = 90*sessionCore.totalSessionStake/100;
uint cPayout = sessionCore.totalSessionStake - tPayout;
(bool sent, ) = payable(Treasury).call{value: tPayout}("");
require(sent);
(bool sent1, ) = payable(msg.sender).call{value: cPayout}("");
require(sent1);
sessionCore.totalSessionStake = 0;
emit sessionEnded(nftAddress, tokenid, nftNonce[nftAddress][tokenid]);
}
/* ======== FUND INCREASE ======== */
/// @notice allow any user to add additional bounty on session of their choice
function addToBounty(address nftAddress, uint tokenid) payable external {
require(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp);
NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake += msg.value;
}
/// @notice allow any user to support any user of their choice
function addToAppraisal(address nftAddress, uint tokenid, address user) payable external {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[user] == 1
&& NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].endTime > block.timestamp
);
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].nftVotes[user].stake += msg.value;
}
/* ======== VIEW FUNCTIONS ======== */
function getStatus(address nftAddress, uint tokenid) view public returns(uint) {
VotingSessionChecks storage sessionCheck = NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid];
return sessionCheck.sessionProgression;
}
function ethToAbc() view public returns(uint) {
return 1e18 / (0.00005 ether + 0.000015 ether * IABCTreasury(Treasury).tokensClaimed() / 1000000);
}
function getEthPayout(address nftAddress, uint tokenid) view external returns(uint) {
if(NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints == 0) {
return 0;
}
return NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalSessionStake * NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].winnerPoints[msg.sender] / NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].totalWinnerPoints;
}
function getVoterCheck(address nftAddress, uint tokenid, address _user) view external returns(uint) {
return NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[_user];
}
/* ======== FALLBACK FUNCTIONS ======== */
receive() external payable {}
fallback() external payable {}
/* ======== MODIFIERS ======== */
modifier stopOverwrite(
address nftAddress,
uint tokenid
) {
require(
nftNonce[nftAddress][tokenid] == 0
|| getStatus(nftAddress, tokenid) == 6
);
_;
}
modifier properVote(
address nftAddress,
uint tokenid
) {
require(
NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] == 0
&& msg.value >= 0.005 ether
);
_;
}
modifier checkParticipation(
address nftAddress,
uint tokenid
) {
require(NftSessionMap[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].voterCheck[msg.sender] > 0);
_;
}
modifier checkHarvestLoss(
address nftAddress,
uint tokenid
) {
require(
NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].sessionProgression == 3
|| block.timestamp > (NftSessionCheck[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].timeFinalAppraisalSet + NftSessionCore[nftNonce[nftAddress][tokenid]][nftAddress][tokenid].votingTime)
);
_;
}
}
|
/// @author Medici
/// @title Pricing session contract for Abacus
|
NatSpecSingleLine
|
/* ======== FALLBACK FUNCTIONS ======== */
|
Comment
|
v0.8.0+commit.c7dfd78e
|
{
"func_code_index": [
19864,
19897
]
}
| 54,977 |
||||
SCC
|
SCC.sol
|
0xa8ed0d8a96a5296d942b72e4d59fcf045dc3ccdf
|
Solidity
|
SCC
|
contract SCC is SafeMath{
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function SCC(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
if (_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) {
if(msg.sender != owner)throw;
owner.transfer(amount);
}
// can accept ether
function() payable {
}
}
|
SCC
|
function SCC(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
ner = msg.sender;
}
|
/* Initializes contract with initial supply tokens to the creator of the contract */
|
Comment
|
v0.4.12+commit.194ff033
|
None
|
bzzr://f8aa4b690b86c917411f57e25423d60cf8403fa6fc03be59353017cc3de9d30e
|
{
"func_code_index": [
988,
1651
]
}
| 54,978 |
||
SCC
|
SCC.sol
|
0xa8ed0d8a96a5296d942b72e4d59fcf045dc3ccdf
|
Solidity
|
SCC
|
contract SCC is SafeMath{
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function SCC(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
if (_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) {
if(msg.sender != owner)throw;
owner.transfer(amount);
}
// can accept ether
function() payable {
}
}
|
transfer
|
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
(_value <= 0) throw;
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
|
/* Send coins */
|
Comment
|
v0.4.12+commit.194ff033
|
None
|
bzzr://f8aa4b690b86c917411f57e25423d60cf8403fa6fc03be59353017cc3de9d30e
|
{
"func_code_index": [
1676,
2439
]
}
| 54,979 |
||
SCC
|
SCC.sol
|
0xa8ed0d8a96a5296d942b72e4d59fcf045dc3ccdf
|
Solidity
|
SCC
|
contract SCC is SafeMath{
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function SCC(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
if (_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) {
if(msg.sender != owner)throw;
owner.transfer(amount);
}
// can accept ether
function() payable {
}
}
|
approve
|
function approve(address _spender, uint256 _value)
returns (bool success) {
(_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
return true;
}
|
/* Allow another contract to spend some tokens in your behalf */
|
Comment
|
v0.4.12+commit.194ff033
|
None
|
bzzr://f8aa4b690b86c917411f57e25423d60cf8403fa6fc03be59353017cc3de9d30e
|
{
"func_code_index": [
2512,
2709
]
}
| 54,980 |
||
SCC
|
SCC.sol
|
0xa8ed0d8a96a5296d942b72e4d59fcf045dc3ccdf
|
Solidity
|
SCC
|
contract SCC is SafeMath{
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function SCC(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
if (_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) {
if(msg.sender != owner)throw;
owner.transfer(amount);
}
// can accept ether
function() payable {
}
}
|
transferFrom
|
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
(_value <= 0) throw;
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
|
/* A contract attempts to get the coins */
|
Comment
|
v0.4.12+commit.194ff033
|
None
|
bzzr://f8aa4b690b86c917411f57e25423d60cf8403fa6fc03be59353017cc3de9d30e
|
{
"func_code_index": [
2769,
3694
]
}
| 54,981 |
||
SCC
|
SCC.sol
|
0xa8ed0d8a96a5296d942b72e4d59fcf045dc3ccdf
|
Solidity
|
SCC
|
contract SCC is SafeMath{
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function SCC(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
if (_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) {
if(msg.sender != owner)throw;
owner.transfer(amount);
}
// can accept ether
function() payable {
}
}
|
withdrawEther
|
function withdrawEther(uint256 amount) {
if(msg.sender != owner)throw;
owner.transfer(amount);
}
|
// transfer balance to owner
|
LineComment
|
v0.4.12+commit.194ff033
|
None
|
bzzr://f8aa4b690b86c917411f57e25423d60cf8403fa6fc03be59353017cc3de9d30e
|
{
"func_code_index": [
5205,
5311
]
}
| 54,982 |
||
SCC
|
SCC.sol
|
0xa8ed0d8a96a5296d942b72e4d59fcf045dc3ccdf
|
Solidity
|
SCC
|
contract SCC is SafeMath{
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function SCC(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Amount of decimals for display purposes
owner = msg.sender;
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
if (_value <= 0) throw;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) throw;
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) returns (bool success) {
if (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough
if (_value <= 0) throw;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
Unfreeze(msg.sender, _value);
return true;
}
// transfer balance to owner
function withdrawEther(uint256 amount) {
if(msg.sender != owner)throw;
owner.transfer(amount);
}
// can accept ether
function() payable {
}
}
|
function() payable {
}
|
// can accept ether
|
LineComment
|
v0.4.12+commit.194ff033
|
None
|
bzzr://f8aa4b690b86c917411f57e25423d60cf8403fa6fc03be59353017cc3de9d30e
|
{
"func_code_index": [
5337,
5366
]
}
| 54,983 |
|||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
mintPublic
|
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
|
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
2237,
3071
]
}
| 54,984 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
mintReserve
|
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
|
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
3216,
3502
]
}
| 54,985 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
claimMulesquad
|
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
|
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
3605,
4467
]
}
| 54,986 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
exchange
|
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
|
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
4626,
6066
]
}
| 54,987 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
mintRandomInternal
|
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
|
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
6249,
7062
]
}
| 54,988 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
_mintInternal
|
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
|
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
7225,
7410
]
}
| 54,989 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
burn
|
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
|
/// @dev burn the token specified
/// @param _tokenId token Id to burn
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
7494,
7653
]
}
| 54,990 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
ownedOfType
|
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
|
/// @dev return total amount of tokens of a type owned by wallet
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
7758,
7924
]
}
| 54,991 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
mintedTotal
|
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
|
/// @dev return total amount of tokens minted
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
7978,
8176
]
}
| 54,992 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
walletOfOwner
|
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
|
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
8310,
8942
]
}
| 54,993 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
tokenURI
|
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
|
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
9048,
9488
]
}
| 54,994 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
getSupplyByType
|
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
|
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
9615,
9778
]
}
| 54,995 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
reveal
|
function reveal() external onlyOwner {
revealed=true;
}
|
/// @dev reveal the real links to metadata
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
9866,
9940
]
}
| 54,996 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
mulesquadClaimEnd
|
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
|
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
10033,
10139
]
}
| 54,997 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
switchMintAllowed
|
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
|
/// @dev switch mint allowed status
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
10183,
10279
]
}
| 54,998 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
switchExchangeAllowed
|
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
|
/// @dev switch exchange allowed status
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
10327,
10435
]
}
| 54,999 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
switchClaimAllowed
|
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
|
/// @dev switch claim allowed status
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
10480,
10579
]
}
| 55,000 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
setMaxPerWallet
|
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
|
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
10688,
10802
]
}
| 55,001 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
setBaseTokenURI
|
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
|
/// @dev Set base URI for tokenURI
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
10845,
10959
]
}
| 55,002 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
transferOwnership
|
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
|
/// @dev transfer ownership
/// @param owner_ new contract owner
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
11187,
11285
]
}
| 55,003 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
withdrawEther
|
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
|
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
11363,
11648
]
}
| 55,004 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
_getRandom
|
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
|
/// @dev get pseudo random uint
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
11722,
12207
]
}
| 55,005 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
balanceOf
|
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
|
/// @dev override to prohibit to get results in same block as random was rolled
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
13789,
14033
]
}
| 55,006 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
ownerOf
|
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
|
/// @dev override to prohibit to get results in same block as random was rolled
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
14121,
14391
]
}
| 55,007 |
||||
CryptoShack
|
contracts/cryptoshack.sol
|
0x34997f9c19465ec01b7ed2ab0e61e2a388702790
|
Solidity
|
CryptoShack
|
contract CryptoShack is ERC721, ReentrancyGuard {
string _baseTokenURI;
address public owner;
IMulesquad internal mulesquadContract = IMulesquad(0xa088AC5a19c28c882D71725C268244b233CFFC62);
uint constant public MAX_SUPPLY = 7200;
uint constant public mintCost = 0.069 ether;
uint constant public maxMintPerTx = 3;
uint public maxPerWallet = 20;
// external counter instead of ERC721Enumerable:totalSupply()
uint256 public totalSupply;
uint256 public publicMinted;
uint256 public reserveMinted;
uint256 public teamReserved = 300;
uint256 public mulesquadClaimed;
uint256 public mulesquadReserved = 690;
// more random, rolled on noContracts
bytes32 private entropySauce;
uint private NOUNCE;
// some numbers and trackers type-based
uint[4][5] private typeToNumbers;
bytes32[5] private typeToNames;
// amount of tokens minted by wallet
mapping(address => uint) private walletToMinted;
// address to amount of tokens of every type owned
mapping(address => uint[5]) private addressToTypesOwned;
// address to last action block number
mapping(address => uint) private callerToLastBlockAction;
// map show if mulesquad ID was used to claim token or not
mapping(uint => bool) private mulesquadIdToClaimed;
bool public mintAllowed;
bool public exchangeAllowed;
bool public claimAllowed;
bool public revealed;
constructor() ERC721("CryptoShack", "SHACK") {
owner=msg.sender;
typeToNames[0]="gophers";
typeToNames[1]="golden_gophers";
typeToNames[2]="caddies";
typeToNames[3]="legendaries";
typeToNames[4]="members";
// minted, burned, exchange scores, max amount
typeToNumbers[0]=[0, 0, 1, 4700]; // GOPHER
typeToNumbers[1]=[0, 0, 4, 150]; // GOLDEN_GOPHER
typeToNumbers[2]=[0, 0, 2, 2350]; // CADDIE
typeToNumbers[3]=[0, 0, 0, 18]; // LEGENDARIES
typeToNumbers[4]=[0, 0, 0, 2500]; // MEMBER
}
//
// MINT
//
/// @dev mint tokens at public sale
/// @param amount_ amount of tokens to mint
function mintPublic(uint amount_) external payable onlyMintAllowed noContracts nonReentrant {
require(msg.value == mintCost * amount_, "Invalid tx value!"); //NOTE: check payment amount
require(publicMinted + amount_ <= MAX_SUPPLY - teamReserved - mulesquadReserved, "No public mint available"); //NOTE: check if GOPHERS left to mint
require(amount_ > 0 && amount_ <= maxMintPerTx, "Wrong mint amount"); //NOTE: check if amount is correct
require(walletToMinted[msg.sender] + amount_ <= maxPerWallet, "Wallet limit reached"); //NOTE: check max per wallet limit
totalSupply+=amount_;
publicMinted+=amount_;
mintRandomInternal(amount_, msg.sender, false);
}
/// @dev mint tokens reserved for the team
/// @param wallet wallet to mint tokens
/// @param amount_ amount of tokens to mint
function mintReserve(address wallet, uint amount_) external onlyOwner noContracts nonReentrant {
require(reserveMinted + amount_ <= teamReserved);
totalSupply+=amount_;
reserveMinted+=amount_;
mintRandomInternal(amount_,wallet, true);
}
/// @dev claim token with mulesquad token Id
/// @param _mulesquadIds mulesquad token Id
function claimMulesquad(uint[] calldata _mulesquadIds) external onlyClaimAllowed noContracts nonReentrant {
require(_mulesquadIds.length > 0, "Array can not be empty");
require(mulesquadClaimed + _mulesquadIds.length <= mulesquadReserved);
require(walletToMinted[msg.sender] + _mulesquadIds.length <= maxPerWallet, "Wallet limit reached");
totalSupply+=_mulesquadIds.length;
mulesquadClaimed+=_mulesquadIds.length;
for (uint i;i<_mulesquadIds.length;i++) {
require(mulesquadContract.ownerOf(_mulesquadIds[i])==msg.sender, "You don't own the token");
require(!mulesquadIdToClaimed[_mulesquadIds[i]], "Already used to claim");
mulesquadIdToClaimed[_mulesquadIds[i]]=true;
}
mintRandomInternal(_mulesquadIds.length, msg.sender, false);
}
/// @dev exchange few tokens of type 0-2 to membership card (token types 3-4)
/// @param _tokenIds array of tokens to be exchanged for membership
function exchange(uint[] calldata _tokenIds) external onlyExchangeAllowed noContracts nonReentrant {
require(_tokenIds.length>0, "Array can not be empty");
uint scoresTotal;
for (uint i;i<_tokenIds.length;i++) {
require(_exists(_tokenIds[i]),"Token doesn't exists");
require(msg.sender==ownerOf(_tokenIds[i]), "You are not the owner");
uint scores = typeToNumbers[_tokenIds[i] / 10000][2];
require(scores > 0, "Members can not be burned");
scoresTotal+=scores;
}
require(scoresTotal == 4, "Scores total should be 4");
totalSupply -= (_tokenIds.length-1);
for (uint i;i<_tokenIds.length;i++) {
burn(_tokenIds[i]);
}
// golden gopher burned, roll the special
if (_tokenIds.length==1) {
uint random = _getRandom(msg.sender, "exchange");
// max golden gophers / golden gophers burned
uint leftToMint = 150-typeToNumbers[1][1]+1;
uint accumulated;
for (uint j = 3; j<=4; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%leftToMint < accumulated) {
_mintInternal(msg.sender, j);
break;
}
}
} else {
_mintInternal(msg.sender, 4);
}
}
/// @dev pick the random type (0-2) and mint it to specific address
/// @param amount_ amount of tokens to be minted
/// @param receiver wallet to get minted tokens
function mintRandomInternal(uint amount_, address receiver, bool ignoreWalletRestriction) internal {
if (!ignoreWalletRestriction) {
walletToMinted[receiver]+=amount_;
}
uint leftToMint = MAX_SUPPLY - publicMinted - mulesquadClaimed - reserveMinted + amount_;
uint accumulated;
for (uint i = 0; i < amount_; i++) {
uint random = _getRandom(msg.sender, "mint");
accumulated = 0;
// pick the type to mint
for (uint j = 0; j<3; j++) {
accumulated+=typeToNumbers[j][3]-typeToNumbers[j][0];
if (random%(leftToMint-i) < accumulated) {
_mintInternal(receiver, j);
break;
}
}
}
}
/// @dev mint token of specific type to specified address
/// @param receiver wallet to mint token to
/// @param tokenType type of token to mint
function _mintInternal(address receiver, uint tokenType) internal {
uint mintId = ++typeToNumbers[tokenType][0] + tokenType*10000;
_mint(receiver, mintId);
}
/// @dev burn the token specified
/// @param _tokenId token Id to burn
function burn(uint _tokenId) internal {
uint tokenType=_tokenId / 10000;
typeToNumbers[tokenType][1]++;
_burn(_tokenId);
}
//
// VIEW
//
/// @dev return total amount of tokens of a type owned by wallet
function ownedOfType(address address_, uint type_) external view noSameBlockAsAction returns(uint) {
return addressToTypesOwned[address_][type_];
}
/// @dev return total amount of tokens minted
function mintedTotal() external view returns (uint) {
uint result;
for (uint i=0;i<3;i++) {
result+=typeToNumbers[i][0];
}
return result;
}
/// @dev return the array of tokens owned by wallet, never use from the contract (!)
/// @param address_ wallet to check
function walletOfOwner(address address_, uint type_) external view returns (uint[] memory) {
require(callerToLastBlockAction[address_] < block.number, "Please try again on next block");
uint[] memory _tokens = new uint[](addressToTypesOwned[address_][type_]);
uint index;
uint tokenId;
uint type_minted=typeToNumbers[type_][0];
for (uint j=1;j<=type_minted;j++) {
tokenId=j+type_*10000;
if (_exists(tokenId)) {
if (ownerOf(tokenId)==address_) {_tokens[index++]=(tokenId);}
}
}
return _tokens;
}
/// @dev return the metadata URI for specific token
/// @param _tokenId token to get URI for
function tokenURI(uint _tokenId) public view override noSameBlockAsAction returns (string memory) {
require(_exists(_tokenId), "Token does not exist");
if (!revealed) {
return string(abi.encodePacked(_baseTokenURI, '/unrevealed/json/metadata.json'));
}
return string(abi.encodePacked(_baseTokenURI, '/', typeToNames[_tokenId/10000],'/','json/',Strings.toString(_tokenId%10000)));
}
/// @dev get the actual amount of tokens of specific type
/// @param type_ token type (check typeToNumbers array)
function getSupplyByType(uint type_) external view noSameBlockAsAction returns(uint) {
return typeToNumbers[type_][0]-typeToNumbers[type_][1];
}
//
// ONLY OWNER
//
/// @dev reveal the real links to metadata
function reveal() external onlyOwner {
revealed=true;
}
/// @dev free all Mulesquad reserved tokens for the public sale, can not be reverted
function mulesquadClaimEnd() external onlyOwner {
mulesquadReserved=mulesquadClaimed;
}
/// @dev switch mint allowed status
function switchMintAllowed() external onlyOwner {
mintAllowed=!mintAllowed;
}
/// @dev switch exchange allowed status
function switchExchangeAllowed() external onlyOwner {
exchangeAllowed=!exchangeAllowed;
}
/// @dev switch claim allowed status
function switchClaimAllowed() external onlyOwner {
claimAllowed=!claimAllowed;
}
/// @dev set wallet mint allowance
/// @param maxPerWallet_ new wallet allowance, default is 20
function setMaxPerWallet(uint maxPerWallet_) external onlyOwner {
maxPerWallet=maxPerWallet_;
}
/// @dev Set base URI for tokenURI
function setBaseTokenURI(string memory baseURI_) external onlyOwner {
_baseTokenURI=baseURI_;
}
function setMulesquadContract(address mulesquadAddress_) external onlyOwner {
mulesquadContract=IMulesquad(mulesquadAddress_);
}
/// @dev transfer ownership
/// @param owner_ new contract owner
function transferOwnership(address owner_) external onlyOwner {
owner=owner_;
}
/// @dev withdraw all ETH accumulated, 10% share goes to solidity dev
function withdrawEther() external onlyOwner {
require(address(this).balance > 0);
uint share = address(this).balance/10;
payable(0xdA00D453F87db473BC84221063f4a27298F7FCca).transfer(share);
payable(owner).transfer(address(this).balance);
}
//
// HELPERS
//
/// @dev get pseudo random uint
function _getRandom(address _address, bytes32 _addition) internal returns (uint){
callerToLastBlockAction[tx.origin] = block.number;
return uint256(
keccak256(
abi.encodePacked(
_address,
block.timestamp,
++NOUNCE,
_addition,
block.basefee,
block.timestamp,
entropySauce)));
}
//
// MODIFIERS
//
/// @dev allow execution when mint allowed only
modifier onlyMintAllowed() {
require(mintAllowed, 'Mint not allowed');
_;
}
/// @dev allow execution when claim only
modifier onlyClaimAllowed() {
require(claimAllowed, 'Claim not allowed');
_;
}
/// @dev allow execution when exchange allowed only
modifier onlyExchangeAllowed() {
require(exchangeAllowed, "Exchange not allowed");
_;
}
/// @dev allow execution when caller is owner only
modifier onlyOwner() {
require(owner == msg.sender, "You are not the owner");
_;
}
/// @dev do not allow execution if caller is contract
modifier noContracts() {
uint256 size;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(msg.sender == tx.origin, "tx.origin != msg.sender");
require(size == 0, "Contract calls are not allowed");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
/// @dev don't allow view functions in same block as action that changed the state
modifier noSameBlockAsAction() {
require(callerToLastBlockAction[tx.origin] < block.number, "Please try again on next block");
_;
}
//
// OVERRIDE
//
/// @dev override to prohibit to get results in same block as random was rolled
function balanceOf(address owner_) public view virtual override(ERC721) returns (uint256) {
require(callerToLastBlockAction[owner_] < block.number, "Please try again on next block");
return super.balanceOf(owner_);
}
/// @dev override to prohibit to get results in same block as random was rolled
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address addr = super.ownerOf(tokenId);
require(callerToLastBlockAction[addr] < block.number, "Please try again on next block");
return addr;
}
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
}
|
_beforeTokenTransfer
|
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override virtual {
uint tokenType = tokenId/10000;
if (from!=address(0)) { addressToTypesOwned[from][tokenType]--; }
if (to!=address(0)) { addressToTypesOwned[to][tokenType]++; }
}
|
/// @dev override to track how many of a type wallet hold, required for custom walletOfOwner and ownedOfType
|
NatSpecSingleLine
|
v0.8.7+commit.e28d00a7
|
{
"func_code_index": [
14508,
14841
]
}
| 55,008 |
||||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Ownable
|
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;
}
}
|
/**
* @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.
*/
|
NatSpecMultiLine
|
owner
|
function owner() public view returns (address) {
return _owner;
}
|
/**
* @dev Returns the address of the current owner.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
501,
582
]
}
| 55,009 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Ownable
|
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;
}
}
|
/**
* @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.
*/
|
NatSpecMultiLine
|
renounceOwnership
|
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
|
/**
* @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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
1124,
1273
]
}
| 55,010 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Ownable
|
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;
}
}
|
/**
* @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.
*/
|
NatSpecMultiLine
|
transferOwnership
|
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
|
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
1418,
1696
]
}
| 55,011 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
/**
* @dev 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.
*/
|
NatSpecMultiLine
|
add
|
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
|
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
248,
428
]
}
| 55,012 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
/**
* @dev 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.
*/
|
NatSpecMultiLine
|
sub
|
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 on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
695,
833
]
}
| 55,013 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
/**
* @dev 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.
*/
|
NatSpecMultiLine
|
sub
|
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 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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
1120,
1341
]
}
| 55,014 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
/**
* @dev 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.
*/
|
NatSpecMultiLine
|
mul
|
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
|
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
1584,
2047
]
}
| 55,015 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
/**
* @dev 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.
*/
|
NatSpecMultiLine
|
div
|
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 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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
2505,
2639
]
}
| 55,016 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
/**
* @dev 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.
*/
|
NatSpecMultiLine
|
div
|
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 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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
3117,
3423
]
}
| 55,017 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
/**
* @dev 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.
*/
|
NatSpecMultiLine
|
mod
|
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 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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
3870,
4002
]
}
| 55,018 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
SafeMath
|
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
|
/**
* @dev 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.
*/
|
NatSpecMultiLine
|
mod
|
function mod(
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),
* 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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
4469,
4666
]
}
| 55,019 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
IERC20
|
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 Interface of the ERC20 standard as defined in the EIP.
*/
|
NatSpecMultiLine
|
totalSupply
|
function totalSupply() external view returns (uint256);
|
/**
* @dev Returns the amount of tokens in existence.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
90,
149
]
}
| 55,020 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
IERC20
|
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 Interface of the ERC20 standard as defined in the EIP.
*/
|
NatSpecMultiLine
|
balanceOf
|
function balanceOf(address account) external view returns (uint256);
|
/**
* @dev Returns the amount of tokens owned by `account`.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
228,
300
]
}
| 55,021 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
IERC20
|
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 Interface of the ERC20 standard as defined in the EIP.
*/
|
NatSpecMultiLine
|
transfer
|
function transfer(address recipient, uint256 amount)
external
returns (bool);
|
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
516,
613
]
}
| 55,022 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
IERC20
|
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 Interface of the ERC20 standard as defined in the EIP.
*/
|
NatSpecMultiLine
|
allowance
|
function allowance(address owner, address spender)
external
view
returns (uint256);
|
/**
* @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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
884,
995
]
}
| 55,023 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
IERC20
|
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 Interface of the ERC20 standard as defined in the EIP.
*/
|
NatSpecMultiLine
|
approve
|
function approve(address spender, uint256 amount) external returns (bool);
|
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
1644,
1722
]
}
| 55,024 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
IERC20
|
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 Interface of the ERC20 standard as defined in the EIP.
*/
|
NatSpecMultiLine
|
transferFrom
|
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
|
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
2025,
2156
]
}
| 55,025 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
isContract
|
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
|
/**
* @dev 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
* ====
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
588,
1025
]
}
| 55,026 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
sendValue
|
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 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].
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
1938,
2399
]
}
| 55,027 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionCall
|
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
|
/**
* @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._
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
3136,
3333
]
}
| 55,028 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionCall
|
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 with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
3551,
3779
]
}
| 55,029 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionCallWithValue
|
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-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._
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
4137,
4485
]
}
| 55,030 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Address
|
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
/**
* @dev Collection of functions related to the address type
*/
|
NatSpecMultiLine
|
functionCallWithValue
|
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);
}
|
/**
* @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._
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
4729,
5118
]
}
| 55,031 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
name
|
function name() public view returns (string memory) {
return _name;
}
|
/**
* @dev Returns the name of the token.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
866,
951
]
}
| 55,032 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
symbol
|
function symbol() public view returns (string memory) {
return _symbol;
}
|
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
1060,
1149
]
}
| 55,033 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
decimals
|
function decimals() public view returns (uint8) {
return _decimals;
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
1768,
1853
]
}
| 55,034 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
totalSupply
|
function totalSupply() public virtual override view returns (uint256) {
return _totalSupply;
}
|
/**
* @dev See {IERC20-totalSupply}.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
1909,
2019
]
}
| 55,035 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
balanceOf
|
function balanceOf(address account)
public
virtual
override
view
returns (uint256)
{
return _balances[account];
}
|
/**
* @dev See {IERC20-balanceOf}.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
2073,
2246
]
}
| 55,036 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
transfer
|
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
|
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
2445,
2657
]
}
| 55,037 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
allowance
|
function allowance(address owner, address spender)
public
virtual
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
|
/**
* @dev See {IERC20-allowance}.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
2711,
2908
]
}
| 55,038 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
approve
|
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
|
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
3042,
3248
]
}
| 55,039 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
transferFrom
|
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 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`.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
3704,
4147
]
}
| 55,040 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
increaseAllowance
|
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
4538,
4831
]
}
| 55,041 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
decreaseAllowance
|
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 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`.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
5314,
5704
]
}
| 55,042 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
_transfer
|
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 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`.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
6174,
6772
]
}
| 55,043 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
_mint
|
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 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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
7038,
7412
]
}
| 55,044 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
_burn
|
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 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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
7727,
8175
]
}
| 55,045 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
_approve
|
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 `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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
8594,
8968
]
}
| 55,046 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
_setupDecimals
|
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
|
/**
* @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.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
9287,
9379
]
}
| 55,047 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
ERC20
|
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 virtual override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
virtual
override
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
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
virtual
override
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
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 {}
}
|
/**
* @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}.
*/
|
NatSpecMultiLine
|
_beforeTokenTransfer
|
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
|
/**
* @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].
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
9962,
10087
]
}
| 55,048 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Initializable
|
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(
initializing || isConstructor() || !initialized,
"Contract instance has already been initialized"
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
|
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
|
NatSpecMultiLine
|
isConstructor
|
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
|
/// @dev Returns true if and only if the function is running in the constructor
|
NatSpecSingleLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
857,
1417
]
}
| 55,049 |
||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Degov
|
contract Degov is ERC20, Ownable, Initializable {
using SafeMath for uint256;
uint256 private constant DECIMALS = 18;
/// @notice A record of each accounts delegate
mapping(address => address) public 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 => uint256) 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_,
uint256 previousBalance_,
uint256 newBalance_
);
//The threshold of the total token supply required in order to pass a proposal
uint256 public quorumThreshold = 20;
//The threshold of the total token supply required in order to propose a proposal
uint256 public proposalThreshold = 1;
uint256 public constant TOTAL_SUPPLY = 25000 * 10**DECIMALS;
event LogSetQuorumThresholdRatio(uint256 quorumThreshold_);
event LogSetProposalThresholdRatio(uint256 proposalThreshold_);
constructor() public ERC20("Degov", "DEGOV") {}
/**
* @notice Initialize the token with policy address and pool for the token distribution
* @param degovDaiLpPool_ Address of the pool contract where newly minted degov tokens are sent.
*/
function initialize(address degovDaiLpPool_) external initializer {
_mint(degovDaiLpPool_, TOTAL_SUPPLY);
}
/**
* @notice Sets the quorum threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a vote on a proposal to pass
* @param quorumThreshold_ The new quorum threshold threshold.
*/
function setQuorumThresholdRatio(uint256 quorumThreshold_)
external
onlyOwner
{
require(
quorumThreshold_ > 0 && quorumThreshold <= 100,
"Quorum threshold must be greater than zero and less/equal to 100"
);
require(
quorumThreshold_ >= proposalThreshold,
"Quorum threshold must be great or equal too proposal threshold"
);
quorumThreshold = quorumThreshold_;
emit LogSetQuorumThresholdRatio(quorumThreshold_);
}
/**
* @notice Sets the proposal threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a proposal to be initiated.
* @param proposalThreshold_ The new proposal threshold threshold.
*/
function setProposalThresholdRatio(uint256 proposalThreshold_)
external
onlyOwner
{
require(
proposalThreshold_ > 0 && proposalThreshold_ <= 100,
"Proposal threshold must be greater than zero and less/equal to 100"
);
require(
proposalThreshold_ <= quorumThreshold,
"Proposal threshold must be great or equal too quorum threshold"
);
proposalThreshold = proposalThreshold_;
emit LogSetProposalThresholdRatio(proposalThreshold_);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
super.transfer(recipient, amount);
_moveDelegates(delegates[msg.sender], delegates[recipient], amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
super.transferFrom(sender, recipient, amount);
_moveDelegates(delegates[sender], delegates[recipient], amount);
return true;
}
/**
* @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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
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),
"Degov::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Degov::delegateBySig: invalid nonce"
);
require(now <= expiry, "Degov::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, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"Degov::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);
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)) {
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)) {
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,
"Degov::_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(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
initialize
|
function initialize(address degovDaiLpPool_) external initializer {
_mint(degovDaiLpPool_, TOTAL_SUPPLY);
}
|
/**
* @notice Initialize the token with policy address and pool for the token distribution
* @param degovDaiLpPool_ Address of the pool contract where newly minted degov tokens are sent.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
2355,
2478
]
}
| 55,050 |
||||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Degov
|
contract Degov is ERC20, Ownable, Initializable {
using SafeMath for uint256;
uint256 private constant DECIMALS = 18;
/// @notice A record of each accounts delegate
mapping(address => address) public 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 => uint256) 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_,
uint256 previousBalance_,
uint256 newBalance_
);
//The threshold of the total token supply required in order to pass a proposal
uint256 public quorumThreshold = 20;
//The threshold of the total token supply required in order to propose a proposal
uint256 public proposalThreshold = 1;
uint256 public constant TOTAL_SUPPLY = 25000 * 10**DECIMALS;
event LogSetQuorumThresholdRatio(uint256 quorumThreshold_);
event LogSetProposalThresholdRatio(uint256 proposalThreshold_);
constructor() public ERC20("Degov", "DEGOV") {}
/**
* @notice Initialize the token with policy address and pool for the token distribution
* @param degovDaiLpPool_ Address of the pool contract where newly minted degov tokens are sent.
*/
function initialize(address degovDaiLpPool_) external initializer {
_mint(degovDaiLpPool_, TOTAL_SUPPLY);
}
/**
* @notice Sets the quorum threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a vote on a proposal to pass
* @param quorumThreshold_ The new quorum threshold threshold.
*/
function setQuorumThresholdRatio(uint256 quorumThreshold_)
external
onlyOwner
{
require(
quorumThreshold_ > 0 && quorumThreshold <= 100,
"Quorum threshold must be greater than zero and less/equal to 100"
);
require(
quorumThreshold_ >= proposalThreshold,
"Quorum threshold must be great or equal too proposal threshold"
);
quorumThreshold = quorumThreshold_;
emit LogSetQuorumThresholdRatio(quorumThreshold_);
}
/**
* @notice Sets the proposal threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a proposal to be initiated.
* @param proposalThreshold_ The new proposal threshold threshold.
*/
function setProposalThresholdRatio(uint256 proposalThreshold_)
external
onlyOwner
{
require(
proposalThreshold_ > 0 && proposalThreshold_ <= 100,
"Proposal threshold must be greater than zero and less/equal to 100"
);
require(
proposalThreshold_ <= quorumThreshold,
"Proposal threshold must be great or equal too quorum threshold"
);
proposalThreshold = proposalThreshold_;
emit LogSetProposalThresholdRatio(proposalThreshold_);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
super.transfer(recipient, amount);
_moveDelegates(delegates[msg.sender], delegates[recipient], amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
super.transferFrom(sender, recipient, amount);
_moveDelegates(delegates[sender], delegates[recipient], amount);
return true;
}
/**
* @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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
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),
"Degov::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Degov::delegateBySig: invalid nonce"
);
require(now <= expiry, "Degov::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, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"Degov::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);
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)) {
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)) {
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,
"Degov::_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(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
setQuorumThresholdRatio
|
function setQuorumThresholdRatio(uint256 quorumThreshold_)
external
onlyOwner
{
require(
quorumThreshold_ > 0 && quorumThreshold <= 100,
"Quorum threshold must be greater than zero and less/equal to 100"
);
require(
quorumThreshold_ >= proposalThreshold,
"Quorum threshold must be great or equal too proposal threshold"
);
quorumThreshold = quorumThreshold_;
emit LogSetQuorumThresholdRatio(quorumThreshold_);
}
|
/**
* @notice Sets the quorum threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a vote on a proposal to pass
* @param quorumThreshold_ The new quorum threshold threshold.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
2730,
3265
]
}
| 55,051 |
||||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Degov
|
contract Degov is ERC20, Ownable, Initializable {
using SafeMath for uint256;
uint256 private constant DECIMALS = 18;
/// @notice A record of each accounts delegate
mapping(address => address) public 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 => uint256) 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_,
uint256 previousBalance_,
uint256 newBalance_
);
//The threshold of the total token supply required in order to pass a proposal
uint256 public quorumThreshold = 20;
//The threshold of the total token supply required in order to propose a proposal
uint256 public proposalThreshold = 1;
uint256 public constant TOTAL_SUPPLY = 25000 * 10**DECIMALS;
event LogSetQuorumThresholdRatio(uint256 quorumThreshold_);
event LogSetProposalThresholdRatio(uint256 proposalThreshold_);
constructor() public ERC20("Degov", "DEGOV") {}
/**
* @notice Initialize the token with policy address and pool for the token distribution
* @param degovDaiLpPool_ Address of the pool contract where newly minted degov tokens are sent.
*/
function initialize(address degovDaiLpPool_) external initializer {
_mint(degovDaiLpPool_, TOTAL_SUPPLY);
}
/**
* @notice Sets the quorum threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a vote on a proposal to pass
* @param quorumThreshold_ The new quorum threshold threshold.
*/
function setQuorumThresholdRatio(uint256 quorumThreshold_)
external
onlyOwner
{
require(
quorumThreshold_ > 0 && quorumThreshold <= 100,
"Quorum threshold must be greater than zero and less/equal to 100"
);
require(
quorumThreshold_ >= proposalThreshold,
"Quorum threshold must be great or equal too proposal threshold"
);
quorumThreshold = quorumThreshold_;
emit LogSetQuorumThresholdRatio(quorumThreshold_);
}
/**
* @notice Sets the proposal threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a proposal to be initiated.
* @param proposalThreshold_ The new proposal threshold threshold.
*/
function setProposalThresholdRatio(uint256 proposalThreshold_)
external
onlyOwner
{
require(
proposalThreshold_ > 0 && proposalThreshold_ <= 100,
"Proposal threshold must be greater than zero and less/equal to 100"
);
require(
proposalThreshold_ <= quorumThreshold,
"Proposal threshold must be great or equal too quorum threshold"
);
proposalThreshold = proposalThreshold_;
emit LogSetProposalThresholdRatio(proposalThreshold_);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
super.transfer(recipient, amount);
_moveDelegates(delegates[msg.sender], delegates[recipient], amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
super.transferFrom(sender, recipient, amount);
_moveDelegates(delegates[sender], delegates[recipient], amount);
return true;
}
/**
* @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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
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),
"Degov::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Degov::delegateBySig: invalid nonce"
);
require(now <= expiry, "Degov::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, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"Degov::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);
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)) {
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)) {
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,
"Degov::_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(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
setProposalThresholdRatio
|
function setProposalThresholdRatio(uint256 proposalThreshold_)
external
onlyOwner
{
require(
proposalThreshold_ > 0 && proposalThreshold_ <= 100,
"Proposal threshold must be greater than zero and less/equal to 100"
);
require(
proposalThreshold_ <= quorumThreshold,
"Proposal threshold must be great or equal too quorum threshold"
);
proposalThreshold = proposalThreshold_;
emit LogSetProposalThresholdRatio(proposalThreshold_);
}
|
/**
* @notice Sets the proposal threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a proposal to be initiated.
* @param proposalThreshold_ The new proposal threshold threshold.
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
3522,
4076
]
}
| 55,052 |
||||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Degov
|
contract Degov is ERC20, Ownable, Initializable {
using SafeMath for uint256;
uint256 private constant DECIMALS = 18;
/// @notice A record of each accounts delegate
mapping(address => address) public 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 => uint256) 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_,
uint256 previousBalance_,
uint256 newBalance_
);
//The threshold of the total token supply required in order to pass a proposal
uint256 public quorumThreshold = 20;
//The threshold of the total token supply required in order to propose a proposal
uint256 public proposalThreshold = 1;
uint256 public constant TOTAL_SUPPLY = 25000 * 10**DECIMALS;
event LogSetQuorumThresholdRatio(uint256 quorumThreshold_);
event LogSetProposalThresholdRatio(uint256 proposalThreshold_);
constructor() public ERC20("Degov", "DEGOV") {}
/**
* @notice Initialize the token with policy address and pool for the token distribution
* @param degovDaiLpPool_ Address of the pool contract where newly minted degov tokens are sent.
*/
function initialize(address degovDaiLpPool_) external initializer {
_mint(degovDaiLpPool_, TOTAL_SUPPLY);
}
/**
* @notice Sets the quorum threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a vote on a proposal to pass
* @param quorumThreshold_ The new quorum threshold threshold.
*/
function setQuorumThresholdRatio(uint256 quorumThreshold_)
external
onlyOwner
{
require(
quorumThreshold_ > 0 && quorumThreshold <= 100,
"Quorum threshold must be greater than zero and less/equal to 100"
);
require(
quorumThreshold_ >= proposalThreshold,
"Quorum threshold must be great or equal too proposal threshold"
);
quorumThreshold = quorumThreshold_;
emit LogSetQuorumThresholdRatio(quorumThreshold_);
}
/**
* @notice Sets the proposal threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a proposal to be initiated.
* @param proposalThreshold_ The new proposal threshold threshold.
*/
function setProposalThresholdRatio(uint256 proposalThreshold_)
external
onlyOwner
{
require(
proposalThreshold_ > 0 && proposalThreshold_ <= 100,
"Proposal threshold must be greater than zero and less/equal to 100"
);
require(
proposalThreshold_ <= quorumThreshold,
"Proposal threshold must be great or equal too quorum threshold"
);
proposalThreshold = proposalThreshold_;
emit LogSetProposalThresholdRatio(proposalThreshold_);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
super.transfer(recipient, amount);
_moveDelegates(delegates[msg.sender], delegates[recipient], amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
super.transferFrom(sender, recipient, amount);
_moveDelegates(delegates[sender], delegates[recipient], amount);
return true;
}
/**
* @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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
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),
"Degov::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Degov::delegateBySig: invalid nonce"
);
require(now <= expiry, "Degov::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, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"Degov::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);
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)) {
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)) {
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,
"Degov::_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(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
delegate
|
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
|
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
4214,
4318
]
}
| 55,053 |
||||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Degov
|
contract Degov is ERC20, Ownable, Initializable {
using SafeMath for uint256;
uint256 private constant DECIMALS = 18;
/// @notice A record of each accounts delegate
mapping(address => address) public 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 => uint256) 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_,
uint256 previousBalance_,
uint256 newBalance_
);
//The threshold of the total token supply required in order to pass a proposal
uint256 public quorumThreshold = 20;
//The threshold of the total token supply required in order to propose a proposal
uint256 public proposalThreshold = 1;
uint256 public constant TOTAL_SUPPLY = 25000 * 10**DECIMALS;
event LogSetQuorumThresholdRatio(uint256 quorumThreshold_);
event LogSetProposalThresholdRatio(uint256 proposalThreshold_);
constructor() public ERC20("Degov", "DEGOV") {}
/**
* @notice Initialize the token with policy address and pool for the token distribution
* @param degovDaiLpPool_ Address of the pool contract where newly minted degov tokens are sent.
*/
function initialize(address degovDaiLpPool_) external initializer {
_mint(degovDaiLpPool_, TOTAL_SUPPLY);
}
/**
* @notice Sets the quorum threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a vote on a proposal to pass
* @param quorumThreshold_ The new quorum threshold threshold.
*/
function setQuorumThresholdRatio(uint256 quorumThreshold_)
external
onlyOwner
{
require(
quorumThreshold_ > 0 && quorumThreshold <= 100,
"Quorum threshold must be greater than zero and less/equal to 100"
);
require(
quorumThreshold_ >= proposalThreshold,
"Quorum threshold must be great or equal too proposal threshold"
);
quorumThreshold = quorumThreshold_;
emit LogSetQuorumThresholdRatio(quorumThreshold_);
}
/**
* @notice Sets the proposal threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a proposal to be initiated.
* @param proposalThreshold_ The new proposal threshold threshold.
*/
function setProposalThresholdRatio(uint256 proposalThreshold_)
external
onlyOwner
{
require(
proposalThreshold_ > 0 && proposalThreshold_ <= 100,
"Proposal threshold must be greater than zero and less/equal to 100"
);
require(
proposalThreshold_ <= quorumThreshold,
"Proposal threshold must be great or equal too quorum threshold"
);
proposalThreshold = proposalThreshold_;
emit LogSetProposalThresholdRatio(proposalThreshold_);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
super.transfer(recipient, amount);
_moveDelegates(delegates[msg.sender], delegates[recipient], amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
super.transferFrom(sender, recipient, amount);
_moveDelegates(delegates[sender], delegates[recipient], amount);
return true;
}
/**
* @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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
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),
"Degov::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Degov::delegateBySig: invalid nonce"
);
require(now <= expiry, "Degov::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, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"Degov::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);
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)) {
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)) {
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,
"Degov::_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(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
delegateBySig
|
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
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),
"Degov::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Degov::delegateBySig: invalid nonce"
);
require(now <= expiry, "Degov::delegateBySig: signature expired");
return _delegate(signatory, 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
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
5299,
6360
]
}
| 55,054 |
||||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Degov
|
contract Degov is ERC20, Ownable, Initializable {
using SafeMath for uint256;
uint256 private constant DECIMALS = 18;
/// @notice A record of each accounts delegate
mapping(address => address) public 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 => uint256) 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_,
uint256 previousBalance_,
uint256 newBalance_
);
//The threshold of the total token supply required in order to pass a proposal
uint256 public quorumThreshold = 20;
//The threshold of the total token supply required in order to propose a proposal
uint256 public proposalThreshold = 1;
uint256 public constant TOTAL_SUPPLY = 25000 * 10**DECIMALS;
event LogSetQuorumThresholdRatio(uint256 quorumThreshold_);
event LogSetProposalThresholdRatio(uint256 proposalThreshold_);
constructor() public ERC20("Degov", "DEGOV") {}
/**
* @notice Initialize the token with policy address and pool for the token distribution
* @param degovDaiLpPool_ Address of the pool contract where newly minted degov tokens are sent.
*/
function initialize(address degovDaiLpPool_) external initializer {
_mint(degovDaiLpPool_, TOTAL_SUPPLY);
}
/**
* @notice Sets the quorum threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a vote on a proposal to pass
* @param quorumThreshold_ The new quorum threshold threshold.
*/
function setQuorumThresholdRatio(uint256 quorumThreshold_)
external
onlyOwner
{
require(
quorumThreshold_ > 0 && quorumThreshold <= 100,
"Quorum threshold must be greater than zero and less/equal to 100"
);
require(
quorumThreshold_ >= proposalThreshold,
"Quorum threshold must be great or equal too proposal threshold"
);
quorumThreshold = quorumThreshold_;
emit LogSetQuorumThresholdRatio(quorumThreshold_);
}
/**
* @notice Sets the proposal threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a proposal to be initiated.
* @param proposalThreshold_ The new proposal threshold threshold.
*/
function setProposalThresholdRatio(uint256 proposalThreshold_)
external
onlyOwner
{
require(
proposalThreshold_ > 0 && proposalThreshold_ <= 100,
"Proposal threshold must be greater than zero and less/equal to 100"
);
require(
proposalThreshold_ <= quorumThreshold,
"Proposal threshold must be great or equal too quorum threshold"
);
proposalThreshold = proposalThreshold_;
emit LogSetProposalThresholdRatio(proposalThreshold_);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
super.transfer(recipient, amount);
_moveDelegates(delegates[msg.sender], delegates[recipient], amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
super.transferFrom(sender, recipient, amount);
_moveDelegates(delegates[sender], delegates[recipient], amount);
return true;
}
/**
* @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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
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),
"Degov::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Degov::delegateBySig: invalid nonce"
);
require(now <= expiry, "Degov::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, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"Degov::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);
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)) {
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)) {
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,
"Degov::_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(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
getCurrentVotes
|
function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return
nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
|
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
6550,
6786
]
}
| 55,055 |
||||
Degov
|
contracts/flattened/Degov.sol
|
0x469e66e06fec34839e5eb1273ba85a119b8d702f
|
Solidity
|
Degov
|
contract Degov is ERC20, Ownable, Initializable {
using SafeMath for uint256;
uint256 private constant DECIMALS = 18;
/// @notice A record of each accounts delegate
mapping(address => address) public 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 => uint256) 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_,
uint256 previousBalance_,
uint256 newBalance_
);
//The threshold of the total token supply required in order to pass a proposal
uint256 public quorumThreshold = 20;
//The threshold of the total token supply required in order to propose a proposal
uint256 public proposalThreshold = 1;
uint256 public constant TOTAL_SUPPLY = 25000 * 10**DECIMALS;
event LogSetQuorumThresholdRatio(uint256 quorumThreshold_);
event LogSetProposalThresholdRatio(uint256 proposalThreshold_);
constructor() public ERC20("Degov", "DEGOV") {}
/**
* @notice Initialize the token with policy address and pool for the token distribution
* @param degovDaiLpPool_ Address of the pool contract where newly minted degov tokens are sent.
*/
function initialize(address degovDaiLpPool_) external initializer {
_mint(degovDaiLpPool_, TOTAL_SUPPLY);
}
/**
* @notice Sets the quorum threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a vote on a proposal to pass
* @param quorumThreshold_ The new quorum threshold threshold.
*/
function setQuorumThresholdRatio(uint256 quorumThreshold_)
external
onlyOwner
{
require(
quorumThreshold_ > 0 && quorumThreshold <= 100,
"Quorum threshold must be greater than zero and less/equal to 100"
);
require(
quorumThreshold_ >= proposalThreshold,
"Quorum threshold must be great or equal too proposal threshold"
);
quorumThreshold = quorumThreshold_;
emit LogSetQuorumThresholdRatio(quorumThreshold_);
}
/**
* @notice Sets the proposal threshold threshold for proposal voting. Used to calculate the % of the total supply required in order for a proposal to be initiated.
* @param proposalThreshold_ The new proposal threshold threshold.
*/
function setProposalThresholdRatio(uint256 proposalThreshold_)
external
onlyOwner
{
require(
proposalThreshold_ > 0 && proposalThreshold_ <= 100,
"Proposal threshold must be greater than zero and less/equal to 100"
);
require(
proposalThreshold_ <= quorumThreshold,
"Proposal threshold must be great or equal too quorum threshold"
);
proposalThreshold = proposalThreshold_;
emit LogSetProposalThresholdRatio(proposalThreshold_);
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
super.transfer(recipient, amount);
_moveDelegates(delegates[msg.sender], delegates[recipient], amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
super.transferFrom(sender, recipient, amount);
_moveDelegates(delegates[sender], delegates[recipient], amount);
return true;
}
/**
* @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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
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),
"Degov::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Degov::delegateBySig: invalid nonce"
);
require(now <= expiry, "Degov::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, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"Degov::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);
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)) {
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)) {
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,
"Degov::_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(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
getPriorVotes
|
function getPriorVotes(address account, uint256 blockNumber)
public
view
returns (uint256)
{
require(
blockNumber < block.number,
"Degov::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;
}
|
/**
* @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
*/
|
NatSpecMultiLine
|
v0.6.6+commit.6c089d02
|
{
"func_code_index": [
7204,
8461
]
}
| 55,056 |
||||
HogeNFTv2
|
HogeNFTv2.sol
|
0x9894b5b1b1ab384cb23bbef6fecacbd994a95c76
|
Solidity
|
EnumerableMap
|
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))));
}
}
|
_set
|
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 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.
*/
|
NatSpecMultiLine
|
v0.7.6+commit.7338295f
|
None
|
ipfs://7c0d11a2c57977e7105ed6f6923de3f5d8b417d24f5b8cd66337f021bfe3f9a1
|
{
"func_code_index": [
1091,
1788
]
}
| 55,057 |
||
HogeNFTv2
|
HogeNFTv2.sol
|
0x9894b5b1b1ab384cb23bbef6fecacbd994a95c76
|
Solidity
|
EnumerableMap
|
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))));
}
}
|
_remove
|
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 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.
*/
|
NatSpecMultiLine
|
v0.7.6+commit.7338295f
|
None
|
ipfs://7c0d11a2c57977e7105ed6f6923de3f5d8b417d24f5b8cd66337f021bfe3f9a1
|
{
"func_code_index": [
1958,
3512
]
}
| 55,058 |
||
HogeNFTv2
|
HogeNFTv2.sol
|
0x9894b5b1b1ab384cb23bbef6fecacbd994a95c76
|
Solidity
|
EnumerableMap
|
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))));
}
}
|
_contains
|
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
|
/**
* @dev Returns true if the key is in the map. O(1).
*/
|
NatSpecMultiLine
|
v0.7.6+commit.7338295f
|
None
|
ipfs://7c0d11a2c57977e7105ed6f6923de3f5d8b417d24f5b8cd66337f021bfe3f9a1
|
{
"func_code_index": [
3591,
3721
]
}
| 55,059 |
||
HogeNFTv2
|
HogeNFTv2.sol
|
0x9894b5b1b1ab384cb23bbef6fecacbd994a95c76
|
Solidity
|
EnumerableMap
|
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))));
}
}
|
_length
|
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
|
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
|
NatSpecMultiLine
|
v0.7.6+commit.7338295f
|
None
|
ipfs://7c0d11a2c57977e7105ed6f6923de3f5d8b417d24f5b8cd66337f021bfe3f9a1
|
{
"func_code_index": [
3811,
3926
]
}
| 55,060 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.