Unnamed: 0
int64 0
7.36k
| comments
stringlengths 3
35.2k
| code_string
stringlengths 1
527k
| code
stringlengths 1
527k
| __index_level_0__
int64 0
88.6k
|
|---|---|---|---|---|
12
|
// Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`.
|
uint256 private constant BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
|
uint256 private constant BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
| 42,068
|
20
|
// These requires are not strictly necessary, our calling code should make sure that these conditions are never broken. However! _createKitty() is already an expensive call (for storage), and it doesn't hurt to be especially careful to ensure our data structures are always valid.
|
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
Kitty memory _kitty = Kitty({
genes: _genes,
birthTime: uint64(_birthTime),
cooldownEndBlock: uint64(_nextActionAt),
matronId: uint32(_matronId),
sireId: uint32(_sireId),
|
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
Kitty memory _kitty = Kitty({
genes: _genes,
birthTime: uint64(_birthTime),
cooldownEndBlock: uint64(_nextActionAt),
matronId: uint32(_matronId),
sireId: uint32(_sireId),
| 3,979
|
7
|
// TODO: Add comment /
|
function burn(uint256 burnQuantity) external returns (bool);
|
function burn(uint256 burnQuantity) external returns (bool);
| 6,925
|
250
|
// allocate tokens to early investor or team member in a batch beneficiary - users who gets tokens allocated amount - amounts of tokens being allocated notStaked - flags if user is eligible for vesting rewards/
|
function allocateUserMultiple(address[] memory beneficiary, uint256[] memory amount, bool[] memory notStaked) public isAdmin() {
uint256 length = beneficiary.length;
require(length <= 346, "Vesting-allocateUserMultiple: List too long");
for (uint256 i = 0; i < length; i++) {
allocateUser(beneficiary[i], amount[i], notStaked[i]);
}
}
|
function allocateUserMultiple(address[] memory beneficiary, uint256[] memory amount, bool[] memory notStaked) public isAdmin() {
uint256 length = beneficiary.length;
require(length <= 346, "Vesting-allocateUserMultiple: List too long");
for (uint256 i = 0; i < length; i++) {
allocateUser(beneficiary[i], amount[i], notStaked[i]);
}
}
| 28,756
|
72
|
// Unique Merchant identifier hash
|
bytes32 public merchantIdHash;
|
bytes32 public merchantIdHash;
| 24,949
|
285
|
// BoredBaldmanYachtClub contract Extends ERC721 Non-Fungible Token Standard basic implementation /
|
contract Baldmanoilclub is ERC721, Ownable {
using SafeMath for uint256;
string public BMOC_PROVENANCE = "";
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint256 public BaldmanPrice = 80000000000000000; //0.08 ETH
uint public constant maxPurchase = 20;
uint256 public MAX_BaldmanS;
bool public saleIsActive = false;
uint256 public REVEAL_TIMESTAMP;
constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 saleStart) ERC721(name, symbol) {
MAX_BaldmanS = maxNftSupply;
REVEAL_TIMESTAMP = saleStart + (86400 * 9);
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function withdrawErc20(address token, uint256 amount) public onlyOwner {
uint balance = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(msg.sender, amount);
}
/**
* Set some Bored Baldmans aside
*/
function reserveBaldmans() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 30; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* DM Gargamel in Discord that you're standing right behind him.
*/
function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = revealTimeStamp;
}
/*
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
BMOC_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
/*
* Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* Mints Bored Baldmans
*/
function mintBaldman(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Baldman");
require(numberOfTokens <= maxPurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_BaldmanS, "Purchase would exceed max supply of Baldmans");
require(BaldmanPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_BaldmanS) {
_safeMint(msg.sender, mintIndex);
}
}
// If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after
// the end of pre-sale, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == MAX_BaldmanS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_BaldmanS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_BaldmanS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
}
|
contract Baldmanoilclub is ERC721, Ownable {
using SafeMath for uint256;
string public BMOC_PROVENANCE = "";
uint256 public startingIndexBlock;
uint256 public startingIndex;
uint256 public BaldmanPrice = 80000000000000000; //0.08 ETH
uint public constant maxPurchase = 20;
uint256 public MAX_BaldmanS;
bool public saleIsActive = false;
uint256 public REVEAL_TIMESTAMP;
constructor(string memory name, string memory symbol, uint256 maxNftSupply, uint256 saleStart) ERC721(name, symbol) {
MAX_BaldmanS = maxNftSupply;
REVEAL_TIMESTAMP = saleStart + (86400 * 9);
}
function withdraw() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
function withdrawErc20(address token, uint256 amount) public onlyOwner {
uint balance = IERC20(token).balanceOf(address(this));
IERC20(token).transfer(msg.sender, amount);
}
/**
* Set some Bored Baldmans aside
*/
function reserveBaldmans() public onlyOwner {
uint supply = totalSupply();
uint i;
for (i = 0; i < 30; i++) {
_safeMint(msg.sender, supply + i);
}
}
/**
* DM Gargamel in Discord that you're standing right behind him.
*/
function setRevealTimestamp(uint256 revealTimeStamp) public onlyOwner {
REVEAL_TIMESTAMP = revealTimeStamp;
}
/*
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
BMOC_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
/*
* Pause sale if active, make active if paused
*/
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
/**
* Mints Bored Baldmans
*/
function mintBaldman(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Baldman");
require(numberOfTokens <= maxPurchase, "Can only mint 20 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_BaldmanS, "Purchase would exceed max supply of Baldmans");
require(BaldmanPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_BaldmanS) {
_safeMint(msg.sender, mintIndex);
}
}
// If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after
// the end of pre-sale, set the starting index block
if (startingIndexBlock == 0 && (totalSupply() == MAX_BaldmanS || block.timestamp >= REVEAL_TIMESTAMP)) {
startingIndexBlock = block.number;
}
}
/**
* Set the starting index for the collection
*/
function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_BaldmanS;
// Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes)
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_BaldmanS;
}
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
/**
* Set the starting index block for the collection, essentially unblocking
* setting starting index
*/
function emergencySetStartingIndexBlock() public onlyOwner {
require(startingIndex == 0, "Starting index is already set");
startingIndexBlock = block.number;
}
}
| 7,380
|
166
|
// Updates the withdrawal penalty/_penalty - the amount of the new penalty (in BIPS)
|
function setWithdrawalPenalty(uint256 _penalty) external onlyOwner {
require(_penalty <= MAX_WITHDRAWAL_PENALTY);
withdrawalPenalty = _penalty;
emit WithdrawalPenaltyUpdated(_penalty);
}
|
function setWithdrawalPenalty(uint256 _penalty) external onlyOwner {
require(_penalty <= MAX_WITHDRAWAL_PENALTY);
withdrawalPenalty = _penalty;
emit WithdrawalPenaltyUpdated(_penalty);
}
| 10,384
|
305
|
// Use to add the new default restriction for all token holder _allowedTokens Amount of tokens allowed to be traded for all token holder. _startTime Unix timestamp at which restriction get into effect _rollingPeriodInDays Rolling period in days (Minimum value should be 1 day) _endTime Unix timestamp at which restriction effects will gets end. _restrictionType Whether it will be `Fixed` (fixed no. of tokens allowed to transact)or `Percentage` (tokens are calculated as per the totalSupply in the fly). /
|
function addDefaultRestriction(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _restrictionType
)
external
withPerm(ADMIN)
|
function addDefaultRestriction(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _restrictionType
)
external
withPerm(ADMIN)
| 33,404
|
0
|
// Authorities
|
address public authority;
|
address public authority;
| 42,564
|
6
|
// (pID => data) player data
|
mapping (uint256 => Player) public plyr_;
|
mapping (uint256 => Player) public plyr_;
| 59,313
|
83
|
// Internal function to update funds for jackpot and dividends weiAmount eth amount in wei /
|
function _addWeiAmount(uint256 weiAmount)
internal
|
function _addWeiAmount(uint256 weiAmount)
internal
| 72,748
|
6
|
// produces new instance with defined name and symbol _info The new instance's inforeturn The new instance's address /
|
function produce(
InstanceInfo memory _info
|
function produce(
InstanceInfo memory _info
| 30,157
|
128
|
// disallow previous dex
|
if (dex[_i] != address(0)) {
reward.safeApprove(dex[_i], 0);
}
|
if (dex[_i] != address(0)) {
reward.safeApprove(dex[_i], 0);
}
| 4,753
|
43
|
// /
|
function setListing(uint256 ticketId, uint256 sellingPrice_)
public
checkSellingPrice(ticketId, sellingPrice_)
checkTicketIsOwner(ticketId, _msgSender())
checkTicketNotOnSale(ticketId)
|
function setListing(uint256 ticketId, uint256 sellingPrice_)
public
checkSellingPrice(ticketId, sellingPrice_)
checkTicketIsOwner(ticketId, _msgSender())
checkTicketNotOnSale(ticketId)
| 6,036
|
2
|
// concatenate six-digit number
|
function createNum() public {
for(uint256 x = 0; x < 9; x++) {
digits(x);
}
}
|
function createNum() public {
for(uint256 x = 0; x < 9; x++) {
digits(x);
}
}
| 44,703
|
96
|
// Emit VotingRightsDelegation
|
emit VotingRightsDelegation(msg.sender, delegate, amount);
|
emit VotingRightsDelegation(msg.sender, delegate, amount);
| 51,451
|
168
|
// info stored for each user's position
|
struct Info {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
// the fees owed to the position owner in token0/token1
uint128 tokensOwed0;
uint128 tokensOwed1;
}
|
struct Info {
// the amount of liquidity owned by this position
uint128 liquidity;
// fee growth per unit of liquidity as of the last update to liquidity or fees owed
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
// the fees owed to the position owner in token0/token1
uint128 tokensOwed0;
uint128 tokensOwed1;
}
| 76,265
|
278
|
// we're done - return the value from the last element
|
return _h[_h.length - 1].v;
|
return _h[_h.length - 1].v;
| 50,174
|
42
|
// ---------------------------------------------------------------------------- DreamFrames Crowdsale Contract - Purchase FrameRush Tokens with ETH
|
// Deployed to : {TBA}
//
// Enjoy.
//
// (c) BokkyPooBah / Bok Consulting Pty Ltd for GazeCoin 2018. The MIT Licence.
// (c) Adrian Guerrera / Deepyr Pty Ltd for Dreamframes 2019. The MIT Licence.
// ----------------------------------------------------------------------------
import "../Shared/Operated.sol";
import "../Shared/SafeMath.sol";
import "../../interfaces/BTTSTokenInterface120.sol";
import "../../interfaces/PriceFeedInterface.sol";
import "../../interfaces/WhiteListInterface.sol";
// ----------------------------------------------------------------------------
// DreamFramesToken Crowdsale Contract
// ----------------------------------------------------------------------------
contract DreamFramesCrowdsale is Operated {
using SafeMath for uint256;
uint256 private constant TENPOW18 = 10 ** 18;
BTTSTokenInterface public dreamFramesToken;
PriceFeedInterface public ethUsdPriceFeed;
WhiteListInterface public bonusList;
address payable public wallet;
uint256 public startDate;
uint256 public endDate;
uint256 public producerPct;
uint256 public frameUsd;
uint256 public framesSold;
bool public finalised;
uint256 public bonusOffList;
uint256 public bonusOnList;
uint256 public contributedUsd;
uint256 public softCapUsd;
uint256 public hardCapUsd;
uint256 public lockedAccountThresholdUsd;
mapping(address => uint256) public accountUsdAmount;
event WalletUpdated(address indexed oldWallet, address indexed newWallet);
event StartDateUpdated(uint256 oldStartDate, uint256 newStartDate);
event EndDateUpdated(uint256 oldEndDate, uint256 newEndDate);
event FrameUsdUpdated(uint256 oldFrameUsd, uint256 newFrameUsd);
event BonusOffListUpdated(uint256 oldBonusOffList, uint256 newBonusOffList);
event BonusOnListUpdated(uint256 oldBonusOnList, uint256 newBonusOnList);
event BonusListUpdated(address oldBonusList, address newBonusList);
event Purchased(address indexed addr, uint256 frames, uint256 ethToTransfer, uint256 framesSold, uint256 contributedUsd);
constructor() public {
}
/// @notice
function init(address _dreamFramesToken, address _ethUsdPriceFeed, address payable _wallet, uint256 _startDate, uint256 _endDate, uint256 _producerPct, uint256 _frameUsd, uint256 _bonusOffList,uint256 _bonusOnList, uint256 _hardCapUsd, uint256 _softCapUsd) public {
require(_wallet != address(0));
require(_endDate > _startDate);
require(_startDate >= now);
require(_producerPct < 100);
require(_dreamFramesToken != address(0));
require(_ethUsdPriceFeed != address(0) );
initOperated(msg.sender);
dreamFramesToken = BTTSTokenInterface(_dreamFramesToken);
ethUsdPriceFeed = PriceFeedInterface(_ethUsdPriceFeed);
lockedAccountThresholdUsd = 10000;
hardCapUsd = _hardCapUsd;
softCapUsd = _softCapUsd;
frameUsd = _frameUsd;
wallet = _wallet;
startDate = _startDate;
endDate = _endDate;
producerPct = _producerPct;
bonusOffList = _bonusOffList;
bonusOnList = _bonusOnList;
}
// ----------------------------------------------------------------------------
// Setter functions
// ----------------------------------------------------------------------------
function setWallet(address payable _wallet) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_wallet != address(0));
emit WalletUpdated(wallet, _wallet);
wallet = _wallet;
}
function setStartDate(uint256 _startDate) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_startDate >= now); // dev: Already started
emit StartDateUpdated(startDate, _startDate);
startDate = _startDate;
}
function setEndDate(uint256 _endDate) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(endDate >= now); // dev: Already ended
require(_endDate > startDate); // dev: End before the start
emit EndDateUpdated(endDate, _endDate);
endDate = _endDate;
}
function setFrameUsd(uint256 _frameUsd) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_frameUsd > 0); // dev: Frame eq 0
emit FrameUsdUpdated(frameUsd, _frameUsd);
frameUsd = _frameUsd;
}
function setBonusOffList(uint256 _bonusOffList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_bonusOffList < 100); // dev: Bonus over 100
emit BonusOffListUpdated(bonusOffList, _bonusOffList);
bonusOffList = _bonusOffList;
}
function setBonusOnList(uint256 _bonusOnList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_bonusOnList < 100); // dev: Bonus over 100
emit BonusOnListUpdated(bonusOnList, _bonusOnList);
bonusOnList = _bonusOnList;
}
function setBonusList(address _bonusList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
emit BonusListUpdated(address(bonusList), _bonusList);
bonusList = WhiteListInterface(_bonusList);
}
// ----------------------------------------------------------------------------
// Getter functions
// ----------------------------------------------------------------------------
function symbol() public view returns (string memory _symbol) {
_symbol = dreamFramesToken.symbol();
}
function name() public view returns (string memory _name) {
_name = dreamFramesToken.name();
}
function usdRemaining() public view returns (uint256) {
return hardCapUsd.sub(contributedUsd);
}
function pctSold() public view returns (uint256) {
return contributedUsd.mul(100).div(hardCapUsd);
}
function pctRemaining() public view returns (uint256) {
return hardCapUsd.sub(contributedUsd).mul(100).div(hardCapUsd);
}
function getBonus(address _address) public view returns (uint256) {
if (bonusList.isInWhiteList(_address) && bonusOnList > bonusOffList ) {
return bonusOnList;
}
return bonusOffList;
}
/// @notice USD per frame, with bonus
/// @dev e.g., 128.123412344122 * 10^18
function frameUsdWithBonus(address _address) public view returns (uint256 _rate) {
uint256 bonus = getBonus(_address);
_rate = frameUsd.mul(100).div(bonus.add(100));
}
/// @notice USD per Eth from price feed
/// @dev e.g., 171.123232454415 * 10^18
function ethUsd() public view returns (uint256 _rate, bool _live) {
return ethUsdPriceFeed.getRate();
}
/// @dev ETH per frame, e.g., 2.757061128879679264 * 10^18
function frameEth() public view returns (uint256 _rate, bool _live) {
uint256 _ethUsd;
(_ethUsd, _live) = ethUsd();
if (_live) {
_rate = frameUsd.mul(TENPOW18).div(_ethUsd);
}
}
/// @dev ETH per frame, e.g., 2.757061128879679264 * 10^18 - including any bonuses
function frameEthBonus(address _address) public view returns (uint256 _rate, bool _live) {
uint256 _ethUsd;
(_ethUsd, _live) = ethUsd();
if (_live) {
_rate = frameUsdWithBonus(_address).mul(TENPOW18).div(_ethUsd);
}
}
function calculateFrames(uint256 _ethAmount) public view returns (uint256 frames, uint256 ethToTransfer) {
return calculateEthFrames(_ethAmount, msg.sender);
}
function calculateUsdFrames(uint256 _usdAmount, address _tokenOwner) public view returns (uint256 frames, uint256 usdToTransfer) {
usdToTransfer = _usdAmount;
if (contributedUsd.add(usdToTransfer) > hardCapUsd) {
usdToTransfer = hardCapUsd.sub(contributedUsd);
}
// Get number of frames available to be purchased
frames = usdToTransfer.div(frameUsdWithBonus(_tokenOwner));
}
/// @notice Get frameEth rate including any bonuses
function calculateEthFrames(uint256 _ethAmount, address _tokenOwner) public view returns (uint256 frames, uint256 ethToTransfer) {
uint256 _frameEth;
uint256 _ethUsd;
bool _live;
(_ethUsd, _live) = ethUsd();
require(_live); // dev: Pricefeed not live
(_frameEth, _live) = frameEthBonus(_tokenOwner);
require(_live); // dev: Pricefeed not live
// USD able to be spent on available frames
uint256 usdAmount = _ethAmount.mul(_ethUsd).div(TENPOW18);
(frames, usdAmount) = calculateUsdFrames(usdAmount,_tokenOwner);
// Return ETH required for available frames
ethToTransfer = frames.mul(_frameEth);
}
// ----------------------------------------------------------------------------
// Crowd sale payments
// ----------------------------------------------------------------------------
/// @notice Buy FrameTokens by sending ETH to this contract address
receive() external payable {
buyFramesEth();
}
/// @notice Or calling this function and sending ETH
function buyFramesEth() public payable {
// Get number of frames remaining
uint256 ethToTransfer;
uint256 frames;
(frames, ethToTransfer) = calculateEthFrames( msg.value, msg.sender);
// Accept ETH Payments
uint256 ethToRefund = msg.value.sub(ethToTransfer);
if (ethToTransfer > 0) {
wallet.transfer(ethToTransfer);
}
// Return any ETH to be refundedf
if (ethToRefund > 0) {
msg.sender.transfer(ethToRefund);
}
// Claim FrameTokens
claimFrames(msg.sender,frames);
emit Purchased(msg.sender, frames, ethToTransfer, framesSold, contributedUsd);
}
/// @notice Operator allocates frames to tokenOwner for offchain purchases
function offlineFramesPurchase(address _tokenOwner, uint256 _frames) external {
// Only operator and owner can allocate frames offline
require(operators[msg.sender] || owner == msg.sender); // dev: Not operator
claimFrames(_tokenOwner,_frames);
emit Purchased(_tokenOwner, _frames, 0, framesSold, contributedUsd);
}
/// @notice Contract allocates frames to tokenOwner
function claimFrames(address _tokenOwner, uint256 _frames) internal {
require(!finalised, "Sale Finalised");
require(_frames > 0, "No frames available");
require(now >= startDate && now <= endDate, "Sale ended");
// Update crowdsale state
uint256 usdToTransfer = _frames.mul(frameUsdWithBonus(_tokenOwner));
require(contributedUsd.add(usdToTransfer) <= hardCapUsd, "Exceeds Hardcap");
contributedUsd = contributedUsd.add(usdToTransfer);
// Tokens locked and KYC check required if over AccountThresholdUsd
accountUsdAmount[_tokenOwner] = accountUsdAmount[_tokenOwner].add(usdToTransfer);
bool lockAccount = accountUsdAmount[_tokenOwner] > lockedAccountThresholdUsd;
// Mint FrameTokens
require(dreamFramesToken.mint(_tokenOwner, _frames.mul(TENPOW18), lockAccount)); // dev: Not Mintable
framesSold = framesSold.add(_frames);
if (contributedUsd >= hardCapUsd) {
finalised = true;
}
}
/// @notice Contract owner finalises crowdsale
function finalise(address _producer) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised || dreamFramesToken.mintable()); // dev: Already Finalised
require(now > endDate || contributedUsd >= hardCapUsd); // dev: Not Finished
finalised = true;
uint256 totalFrames = framesSold.mul(100).div(uint256(100).sub(producerPct));
uint256 producerFrames = totalFrames.sub(framesSold);
if (producerFrames > 0 && contributedUsd >= softCapUsd ) {
require(dreamFramesToken.mint(_producer, producerFrames.mul(TENPOW18), false)); // dev: Failed final mint
}
dreamFramesToken.disableMinting();
}
}
|
// Deployed to : {TBA}
//
// Enjoy.
//
// (c) BokkyPooBah / Bok Consulting Pty Ltd for GazeCoin 2018. The MIT Licence.
// (c) Adrian Guerrera / Deepyr Pty Ltd for Dreamframes 2019. The MIT Licence.
// ----------------------------------------------------------------------------
import "../Shared/Operated.sol";
import "../Shared/SafeMath.sol";
import "../../interfaces/BTTSTokenInterface120.sol";
import "../../interfaces/PriceFeedInterface.sol";
import "../../interfaces/WhiteListInterface.sol";
// ----------------------------------------------------------------------------
// DreamFramesToken Crowdsale Contract
// ----------------------------------------------------------------------------
contract DreamFramesCrowdsale is Operated {
using SafeMath for uint256;
uint256 private constant TENPOW18 = 10 ** 18;
BTTSTokenInterface public dreamFramesToken;
PriceFeedInterface public ethUsdPriceFeed;
WhiteListInterface public bonusList;
address payable public wallet;
uint256 public startDate;
uint256 public endDate;
uint256 public producerPct;
uint256 public frameUsd;
uint256 public framesSold;
bool public finalised;
uint256 public bonusOffList;
uint256 public bonusOnList;
uint256 public contributedUsd;
uint256 public softCapUsd;
uint256 public hardCapUsd;
uint256 public lockedAccountThresholdUsd;
mapping(address => uint256) public accountUsdAmount;
event WalletUpdated(address indexed oldWallet, address indexed newWallet);
event StartDateUpdated(uint256 oldStartDate, uint256 newStartDate);
event EndDateUpdated(uint256 oldEndDate, uint256 newEndDate);
event FrameUsdUpdated(uint256 oldFrameUsd, uint256 newFrameUsd);
event BonusOffListUpdated(uint256 oldBonusOffList, uint256 newBonusOffList);
event BonusOnListUpdated(uint256 oldBonusOnList, uint256 newBonusOnList);
event BonusListUpdated(address oldBonusList, address newBonusList);
event Purchased(address indexed addr, uint256 frames, uint256 ethToTransfer, uint256 framesSold, uint256 contributedUsd);
constructor() public {
}
/// @notice
function init(address _dreamFramesToken, address _ethUsdPriceFeed, address payable _wallet, uint256 _startDate, uint256 _endDate, uint256 _producerPct, uint256 _frameUsd, uint256 _bonusOffList,uint256 _bonusOnList, uint256 _hardCapUsd, uint256 _softCapUsd) public {
require(_wallet != address(0));
require(_endDate > _startDate);
require(_startDate >= now);
require(_producerPct < 100);
require(_dreamFramesToken != address(0));
require(_ethUsdPriceFeed != address(0) );
initOperated(msg.sender);
dreamFramesToken = BTTSTokenInterface(_dreamFramesToken);
ethUsdPriceFeed = PriceFeedInterface(_ethUsdPriceFeed);
lockedAccountThresholdUsd = 10000;
hardCapUsd = _hardCapUsd;
softCapUsd = _softCapUsd;
frameUsd = _frameUsd;
wallet = _wallet;
startDate = _startDate;
endDate = _endDate;
producerPct = _producerPct;
bonusOffList = _bonusOffList;
bonusOnList = _bonusOnList;
}
// ----------------------------------------------------------------------------
// Setter functions
// ----------------------------------------------------------------------------
function setWallet(address payable _wallet) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_wallet != address(0));
emit WalletUpdated(wallet, _wallet);
wallet = _wallet;
}
function setStartDate(uint256 _startDate) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_startDate >= now); // dev: Already started
emit StartDateUpdated(startDate, _startDate);
startDate = _startDate;
}
function setEndDate(uint256 _endDate) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(endDate >= now); // dev: Already ended
require(_endDate > startDate); // dev: End before the start
emit EndDateUpdated(endDate, _endDate);
endDate = _endDate;
}
function setFrameUsd(uint256 _frameUsd) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_frameUsd > 0); // dev: Frame eq 0
emit FrameUsdUpdated(frameUsd, _frameUsd);
frameUsd = _frameUsd;
}
function setBonusOffList(uint256 _bonusOffList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_bonusOffList < 100); // dev: Bonus over 100
emit BonusOffListUpdated(bonusOffList, _bonusOffList);
bonusOffList = _bonusOffList;
}
function setBonusOnList(uint256 _bonusOnList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
require(_bonusOnList < 100); // dev: Bonus over 100
emit BonusOnListUpdated(bonusOnList, _bonusOnList);
bonusOnList = _bonusOnList;
}
function setBonusList(address _bonusList) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised); // dev: Finalised
emit BonusListUpdated(address(bonusList), _bonusList);
bonusList = WhiteListInterface(_bonusList);
}
// ----------------------------------------------------------------------------
// Getter functions
// ----------------------------------------------------------------------------
function symbol() public view returns (string memory _symbol) {
_symbol = dreamFramesToken.symbol();
}
function name() public view returns (string memory _name) {
_name = dreamFramesToken.name();
}
function usdRemaining() public view returns (uint256) {
return hardCapUsd.sub(contributedUsd);
}
function pctSold() public view returns (uint256) {
return contributedUsd.mul(100).div(hardCapUsd);
}
function pctRemaining() public view returns (uint256) {
return hardCapUsd.sub(contributedUsd).mul(100).div(hardCapUsd);
}
function getBonus(address _address) public view returns (uint256) {
if (bonusList.isInWhiteList(_address) && bonusOnList > bonusOffList ) {
return bonusOnList;
}
return bonusOffList;
}
/// @notice USD per frame, with bonus
/// @dev e.g., 128.123412344122 * 10^18
function frameUsdWithBonus(address _address) public view returns (uint256 _rate) {
uint256 bonus = getBonus(_address);
_rate = frameUsd.mul(100).div(bonus.add(100));
}
/// @notice USD per Eth from price feed
/// @dev e.g., 171.123232454415 * 10^18
function ethUsd() public view returns (uint256 _rate, bool _live) {
return ethUsdPriceFeed.getRate();
}
/// @dev ETH per frame, e.g., 2.757061128879679264 * 10^18
function frameEth() public view returns (uint256 _rate, bool _live) {
uint256 _ethUsd;
(_ethUsd, _live) = ethUsd();
if (_live) {
_rate = frameUsd.mul(TENPOW18).div(_ethUsd);
}
}
/// @dev ETH per frame, e.g., 2.757061128879679264 * 10^18 - including any bonuses
function frameEthBonus(address _address) public view returns (uint256 _rate, bool _live) {
uint256 _ethUsd;
(_ethUsd, _live) = ethUsd();
if (_live) {
_rate = frameUsdWithBonus(_address).mul(TENPOW18).div(_ethUsd);
}
}
function calculateFrames(uint256 _ethAmount) public view returns (uint256 frames, uint256 ethToTransfer) {
return calculateEthFrames(_ethAmount, msg.sender);
}
function calculateUsdFrames(uint256 _usdAmount, address _tokenOwner) public view returns (uint256 frames, uint256 usdToTransfer) {
usdToTransfer = _usdAmount;
if (contributedUsd.add(usdToTransfer) > hardCapUsd) {
usdToTransfer = hardCapUsd.sub(contributedUsd);
}
// Get number of frames available to be purchased
frames = usdToTransfer.div(frameUsdWithBonus(_tokenOwner));
}
/// @notice Get frameEth rate including any bonuses
function calculateEthFrames(uint256 _ethAmount, address _tokenOwner) public view returns (uint256 frames, uint256 ethToTransfer) {
uint256 _frameEth;
uint256 _ethUsd;
bool _live;
(_ethUsd, _live) = ethUsd();
require(_live); // dev: Pricefeed not live
(_frameEth, _live) = frameEthBonus(_tokenOwner);
require(_live); // dev: Pricefeed not live
// USD able to be spent on available frames
uint256 usdAmount = _ethAmount.mul(_ethUsd).div(TENPOW18);
(frames, usdAmount) = calculateUsdFrames(usdAmount,_tokenOwner);
// Return ETH required for available frames
ethToTransfer = frames.mul(_frameEth);
}
// ----------------------------------------------------------------------------
// Crowd sale payments
// ----------------------------------------------------------------------------
/// @notice Buy FrameTokens by sending ETH to this contract address
receive() external payable {
buyFramesEth();
}
/// @notice Or calling this function and sending ETH
function buyFramesEth() public payable {
// Get number of frames remaining
uint256 ethToTransfer;
uint256 frames;
(frames, ethToTransfer) = calculateEthFrames( msg.value, msg.sender);
// Accept ETH Payments
uint256 ethToRefund = msg.value.sub(ethToTransfer);
if (ethToTransfer > 0) {
wallet.transfer(ethToTransfer);
}
// Return any ETH to be refundedf
if (ethToRefund > 0) {
msg.sender.transfer(ethToRefund);
}
// Claim FrameTokens
claimFrames(msg.sender,frames);
emit Purchased(msg.sender, frames, ethToTransfer, framesSold, contributedUsd);
}
/// @notice Operator allocates frames to tokenOwner for offchain purchases
function offlineFramesPurchase(address _tokenOwner, uint256 _frames) external {
// Only operator and owner can allocate frames offline
require(operators[msg.sender] || owner == msg.sender); // dev: Not operator
claimFrames(_tokenOwner,_frames);
emit Purchased(_tokenOwner, _frames, 0, framesSold, contributedUsd);
}
/// @notice Contract allocates frames to tokenOwner
function claimFrames(address _tokenOwner, uint256 _frames) internal {
require(!finalised, "Sale Finalised");
require(_frames > 0, "No frames available");
require(now >= startDate && now <= endDate, "Sale ended");
// Update crowdsale state
uint256 usdToTransfer = _frames.mul(frameUsdWithBonus(_tokenOwner));
require(contributedUsd.add(usdToTransfer) <= hardCapUsd, "Exceeds Hardcap");
contributedUsd = contributedUsd.add(usdToTransfer);
// Tokens locked and KYC check required if over AccountThresholdUsd
accountUsdAmount[_tokenOwner] = accountUsdAmount[_tokenOwner].add(usdToTransfer);
bool lockAccount = accountUsdAmount[_tokenOwner] > lockedAccountThresholdUsd;
// Mint FrameTokens
require(dreamFramesToken.mint(_tokenOwner, _frames.mul(TENPOW18), lockAccount)); // dev: Not Mintable
framesSold = framesSold.add(_frames);
if (contributedUsd >= hardCapUsd) {
finalised = true;
}
}
/// @notice Contract owner finalises crowdsale
function finalise(address _producer) public {
require(msg.sender == owner); // dev: Not owner
require(!finalised || dreamFramesToken.mintable()); // dev: Already Finalised
require(now > endDate || contributedUsd >= hardCapUsd); // dev: Not Finished
finalised = true;
uint256 totalFrames = framesSold.mul(100).div(uint256(100).sub(producerPct));
uint256 producerFrames = totalFrames.sub(framesSold);
if (producerFrames > 0 && contributedUsd >= softCapUsd ) {
require(dreamFramesToken.mint(_producer, producerFrames.mul(TENPOW18), false)); // dev: Failed final mint
}
dreamFramesToken.disableMinting();
}
}
| 32,842
|
102
|
// Operator mints basis bonds to a recipient recipient_ The address of recipient amount_ The amount of basis bonds to mint toreturn whether the process has been done /
|
function mint(address recipient_, uint256 amount_)
public
onlyOperator
returns (bool)
{
uint256 balanceBefore = balanceOf(recipient_);
_mint(recipient_, amount_);
uint256 balanceAfter = balanceOf(recipient_);
return balanceAfter > balanceBefore;
|
function mint(address recipient_, uint256 amount_)
public
onlyOperator
returns (bool)
{
uint256 balanceBefore = balanceOf(recipient_);
_mint(recipient_, amount_);
uint256 balanceAfter = balanceOf(recipient_);
return balanceAfter > balanceBefore;
| 11,731
|
18
|
// Returns the addition of two unsigned integers, reverting onoverflow. 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;
}
|
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
| 4,564
|
127
|
// Migration timestamp of this pool, zero means not set Migration timestamp can only be set with a grace period at least 3 days, and the `migrationDestination` pool address must be also set when setting migration timestamp, users can use this grace period to verify the `migrationDestination` pool code
|
uint256 _migrationTimestamp;
|
uint256 _migrationTimestamp;
| 59,738
|
132
|
// Add to liquidity pool
|
if (_autoSwapAndLiquifyEnabled) {
|
if (_autoSwapAndLiquifyEnabled) {
| 20,775
|
18
|
// send borrow rate in 4 decimals from UI. In the smart contract it'll convert to 27 decimals which where is 100%
|
uint128 maxBorrowRate; // maximum borrow rate above this leveraging should not happen
|
uint128 maxBorrowRate; // maximum borrow rate above this leveraging should not happen
| 57,388
|
3
|
// error about that the set time is less than the delay
|
error MinDelay();
|
error MinDelay();
| 36,034
|
315
|
// The encoded chain's ID of Band.
|
bytes public encodedChainID;
|
bytes public encodedChainID;
| 28,402
|
16
|
// Storage slot with the address of the current implementation.This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and isvalidated in the constructor. /
|
bytes32 internal constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
|
bytes32 internal constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
| 17,184
|
3
|
// Move tokens to controller where money will be protected with time lock/_token Token address/amount Token amount
|
function withdrawToController(address _token, uint256 amount) external override onlyController {
uint256 tokenBalance = IERC20(_token).balanceOf(address(this));
require(tokenBalance >= amount, "not enough balance");
IERC20(_token).safeTransfer(_controller(), amount);
emit TokenWithdrawn(_token, amount);
}
|
function withdrawToController(address _token, uint256 amount) external override onlyController {
uint256 tokenBalance = IERC20(_token).balanceOf(address(this));
require(tokenBalance >= amount, "not enough balance");
IERC20(_token).safeTransfer(_controller(), amount);
emit TokenWithdrawn(_token, amount);
}
| 8,051
|
13
|
// Function modifier to require caller to be contract deployer /
|
modifier onlyOwner() {
require(isOwner(msg.sender), "!Owner"); _;
}
|
modifier onlyOwner() {
require(isOwner(msg.sender), "!Owner"); _;
}
| 4,509
|
27
|
// set initial virtual allocation of token0 and token1/init0_ initial virtual allocation of token 0./init1_ initial virtual allocation of token 1./only callable by restrictedMint or by owner if restrictedMint is unset.
|
function setInits(uint256 init0_, uint256 init1_) external {
require(init0_ > 0 || init1_ > 0, "I");
require(totalSupply() == 0, "TS");
address requiredCaller = restrictedMint == address(0)
? owner()
: restrictedMint;
require(msg.sender == requiredCaller, "R");
emit LogSetInits(init0 = init0_, init1 = init1_);
}
|
function setInits(uint256 init0_, uint256 init1_) external {
require(init0_ > 0 || init1_ > 0, "I");
require(totalSupply() == 0, "TS");
address requiredCaller = restrictedMint == address(0)
? owner()
: restrictedMint;
require(msg.sender == requiredCaller, "R");
emit LogSetInits(init0 = init0_, init1 = init1_);
}
| 24,783
|
25
|
// Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}. Two minutes minimum difference between selling and buying time
|
uint256 private minimumDiffSellBuyTime = 2 minutes;
uint256 private _totalSupply = 5000 ether;
string private _name = "LIF4.finance";
string private _symbol = "LIF4";
uint8 private _decimals = 18;
address private __owner;
bool public beginning = true;
bool private limitBuy = true;
|
uint256 private minimumDiffSellBuyTime = 2 minutes;
uint256 private _totalSupply = 5000 ether;
string private _name = "LIF4.finance";
string private _symbol = "LIF4";
uint8 private _decimals = 18;
address private __owner;
bool public beginning = true;
bool private limitBuy = true;
| 17,421
|
117
|
// Initially set token address and admin wallet address
|
constructor(address _token, address _admin, address _rewardToken) {
token = IERC20(_token);
admin = IRBAC(_admin);
rewardToken = IERC20(_rewardToken);
}
|
constructor(address _token, address _admin, address _rewardToken) {
token = IERC20(_token);
admin = IRBAC(_admin);
rewardToken = IERC20(_rewardToken);
}
| 35,688
|
157
|
// Note:: Solidity is kind of terrible in that there is a limit to localvariables that can be put into the stack. The real pain is thatone can put structs, arrays, or mappings into memory but not basicdata types. Hence our payments array that stores these values.
|
uint256[4] memory payments;
|
uint256[4] memory payments;
| 57,508
|
35
|
// First check most recent balance
|
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
|
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
| 26,425
|
14
|
// Update Constants
|
totalSold = totalSold.add(amount);
collectedETH = collectedETH.add(msg.value);
|
totalSold = totalSold.add(amount);
collectedETH = collectedETH.add(msg.value);
| 36,138
|
50
|
// Claims all unclaimed RGT allocated privately to `msg.sender`. /
|
function claimAllPrivateRgt() external {
uint256 unclaimedRgt = getUnclaimedPrivateRgt(msg.sender);
require(unclaimedRgt > 0, "Unclaimed RGT allocated privately not greater than 0.");
_claimPrivateRgt(msg.sender, unclaimedRgt);
}
|
function claimAllPrivateRgt() external {
uint256 unclaimedRgt = getUnclaimedPrivateRgt(msg.sender);
require(unclaimedRgt > 0, "Unclaimed RGT allocated privately not greater than 0.");
_claimPrivateRgt(msg.sender, unclaimedRgt);
}
| 42,105
|
49
|
// Calculate and send tokens to taker and relayer _orderIssuanceOrder object containing order params_fillQuantity Quantity of Set to be filled_requiredMakerTokenAmount Max amount of maker token available to fill orders_makerTokenUsed Amount of maker token used to fill order /
|
function settleAccounts(
OrderLibrary.IssuanceOrder _order,
uint _fillQuantity,
uint _requiredMakerTokenAmount,
uint _makerTokenUsed
)
private
|
function settleAccounts(
OrderLibrary.IssuanceOrder _order,
uint _fillQuantity,
uint _requiredMakerTokenAmount,
uint _makerTokenUsed
)
private
| 28,595
|
231
|
// Can not tranche bonds for 3 days from last execution of this function /
|
function trancheBonds() external override isActive endCoolTime {
uint256 currentPriceE8 = ORACLE.latestPrice();
uint256 bondGroupId = _getSuitableBondGroup(currentPriceE8);
if (bondGroupId == 0) {
bondGroupId = _addSuitableBondGroup(currentPriceE8);
}
(uint256 amount, uint256 ethAmount, uint256[2] memory reverseBonds) = STRATEGY
.getTrancheBonds(
BONDMAKER,
address(this),
bondGroupId,
currentPriceE8,
issuableBondGroupIds[currentTerm],
priceUnit,
REVERSE_ORACLE
);
if (ethAmount > 0) {
DOTC.depositEth{value: ethAmount}();
}
if (amount > 0) {
_issueBonds(bondGroupId, amount);
}
if (reverseBonds[1] > 0) {
// Burn bond and get collateral asset
require(
BONDMAKER.reverseBondGroupToCollateral(reverseBonds[0], reverseBonds[1]),
"Reverse"
);
}
lastTrancheTime = block.timestamp.toUint64();
emit TrancheBond(
uint64(bondGroupId),
uint64(amount),
uint64(reverseBonds[0]),
uint64(reverseBonds[1])
);
}
|
function trancheBonds() external override isActive endCoolTime {
uint256 currentPriceE8 = ORACLE.latestPrice();
uint256 bondGroupId = _getSuitableBondGroup(currentPriceE8);
if (bondGroupId == 0) {
bondGroupId = _addSuitableBondGroup(currentPriceE8);
}
(uint256 amount, uint256 ethAmount, uint256[2] memory reverseBonds) = STRATEGY
.getTrancheBonds(
BONDMAKER,
address(this),
bondGroupId,
currentPriceE8,
issuableBondGroupIds[currentTerm],
priceUnit,
REVERSE_ORACLE
);
if (ethAmount > 0) {
DOTC.depositEth{value: ethAmount}();
}
if (amount > 0) {
_issueBonds(bondGroupId, amount);
}
if (reverseBonds[1] > 0) {
// Burn bond and get collateral asset
require(
BONDMAKER.reverseBondGroupToCollateral(reverseBonds[0], reverseBonds[1]),
"Reverse"
);
}
lastTrancheTime = block.timestamp.toUint64();
emit TrancheBond(
uint64(bondGroupId),
uint64(amount),
uint64(reverseBonds[0]),
uint64(reverseBonds[1])
);
}
| 3,545
|
63
|
// Round bonuses
|
uint256 bonus1 = 10;
uint256 bonus2 = 15;
uint256 bonus3 = 20;
uint256 bonus4 = 30;
|
uint256 bonus1 = 10;
uint256 bonus2 = 15;
uint256 bonus3 = 20;
uint256 bonus4 = 30;
| 10,449
|
1
|
// compute the amount that must be sent to move the price to the profit-maximizing price
|
amountIn = leftSide.sub(rightSide);
|
amountIn = leftSide.sub(rightSide);
| 12,623
|
235
|
// Returns the keccak hash of the ABI-encoded StoredBlockInfo
|
function hashStoredBlockInfo(StoredBlockInfo memory _storedBlockInfo) internal pure returns (bytes32) {
return keccak256(abi.encode(_storedBlockInfo));
}
|
function hashStoredBlockInfo(StoredBlockInfo memory _storedBlockInfo) internal pure returns (bytes32) {
return keccak256(abi.encode(_storedBlockInfo));
}
| 78,431
|
45
|
// Address of manager
|
address public icoOwner;
|
address public icoOwner;
| 27,678
|
40
|
// Direct payout
|
if(users[msg.sender].payouts < max_payout && users[msg.sender].direct_bonus > 0) {
uint256 direct_bonus = users[msg.sender].direct_bonus;
if(users[msg.sender].payouts + direct_bonus > max_payout) {
direct_bonus = max_payout - users[msg.sender].payouts;
}
|
if(users[msg.sender].payouts < max_payout && users[msg.sender].direct_bonus > 0) {
uint256 direct_bonus = users[msg.sender].direct_bonus;
if(users[msg.sender].payouts + direct_bonus > max_payout) {
direct_bonus = max_payout - users[msg.sender].payouts;
}
| 46,170
|
9
|
// Returns the base URI for an image for a given member registry. registry_ The address of the member registry to get the base URI for.return A string representing the base URI for the registry. /
|
function getImageBaseURI(
address registry_
|
function getImageBaseURI(
address registry_
| 39,242
|
56
|
// Adds up to 30 referred investors. To be called one or more timesfor initial referred list loading. _referralCodes keccak-256 hashes of referral codes. _investors corresponding referred investors. /
|
function loadReferredInvestors(bytes32[] _referralCodes, address[] _investors) public onlyOwner
|
function loadReferredInvestors(bytes32[] _referralCodes, address[] _investors) public onlyOwner
| 25,755
|
30
|
// Emision del evento para la nueva atraccion
|
emit nueva_atraccion(_nombreAtraccion, _precio);
|
emit nueva_atraccion(_nombreAtraccion, _precio);
| 41,733
|
71
|
// automatically generates getters
|
uint public constant minInvesment = 10 finney;
uint public constant maxBalance = 333e5 ether;
address public advertisingAddress;
address public adminsAddress;
uint public investmentsNumber;
uint public waveStartup;
|
uint public constant minInvesment = 10 finney;
uint public constant maxBalance = 333e5 ether;
address public advertisingAddress;
address public adminsAddress;
uint public investmentsNumber;
uint public waveStartup;
| 40,433
|
280
|
// Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled/A fee amount can never be removed, so this value should be hard coded or cached in the calling context/fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee/ return The tick spacing
|
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
|
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
| 28,469
|
159
|
// Update a profiterole address//_profiterole profiterole address// return result code of an operation
|
function updateProfiterole(address _profiterole, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_profiterole), _block);
if (OK != _code) {
return _code;
}
profiterole = _profiterole;
return OK;
}
|
function updateProfiterole(address _profiterole, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_profiterole), _block);
if (OK != _code) {
return _code;
}
profiterole = _profiterole;
return OK;
}
| 2,751
|
19
|
// Swap half WETH for token0
|
uint256 _weth = IERC20(weth).balanceOf(address(this));
if (_weth > 0 && token0 != weth) {
_swapSushiswap(weth, token0, _weth.div(2));
}
|
uint256 _weth = IERC20(weth).balanceOf(address(this));
if (_weth > 0 && token0 != weth) {
_swapSushiswap(weth, token0, _weth.div(2));
}
| 41,398
|
59
|
// Returns if a blockchain is in the list of allowed blockchains to cross tokens using the bridge. Parameters: string name of blockchain Returns: boolean true if it is in the list/
|
function existsBlockchain(string memory name)
public
view
override
returns (bool)
|
function existsBlockchain(string memory name)
public
view
override
returns (bool)
| 50,107
|
61
|
// Two sides are fully funded.
|
shadowWinner = NO_SHADOW_WINNER;
arbitrator.appeal.value(appealCost)(session.disputeID, arbitratorExtraData);
session.rounds.length++;
round.feeRewards = round.feeRewards.subCap(appealCost);
reservedETH = reservedETH.subCap(appealCost);
|
shadowWinner = NO_SHADOW_WINNER;
arbitrator.appeal.value(appealCost)(session.disputeID, arbitratorExtraData);
session.rounds.length++;
round.feeRewards = round.feeRewards.subCap(appealCost);
reservedETH = reservedETH.subCap(appealCost);
| 10,398
|
21
|
// Get voters count
|
function getTotalVoter() public view returns (uint256) {
// Returns total number of voters
return voterCount;
}
|
function getTotalVoter() public view returns (uint256) {
// Returns total number of voters
return voterCount;
}
| 1,188
|
16
|
// Require that the Plebness attribute selector has not been locked. /
|
modifier whenPlebnessNotLocked() {
require(!isPlebnessLocked, 'Plebness is locked');
_;
}
|
modifier whenPlebnessNotLocked() {
require(!isPlebnessLocked, 'Plebness is locked');
_;
}
| 25,332
|
335
|
// Get exact ticks depending on Sorbetto's new balances
|
(tickLower, tickUpper) = pool.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing);
cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper);
|
(tickLower, tickUpper) = pool.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing);
cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper);
| 18,757
|
2
|
// Returns the pool for the given token pair and fee. The pool contract may or may not exist.
|
function getPool(
address tokenA,
address tokenB,
uint24 fee
) private view returns (IYumyumSwapPool) {
return IYumyumSwapPool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)));
}
|
function getPool(
address tokenA,
address tokenB,
uint24 fee
) private view returns (IYumyumSwapPool) {
return IYumyumSwapPool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)));
}
| 13,470
|
9
|
// The players' balances, so that at some point they can withdraw (and pay the gas for it)
|
mapping(address => uint) public balances;
event LogGameCreated(string gameName, address playerAddress);
event LogPlayerDeclares(string gameName, address playerAddress);
event LogPlayerReveals(string gameName, address playerAddress, string move);
|
mapping(address => uint) public balances;
event LogGameCreated(string gameName, address playerAddress);
event LogPlayerDeclares(string gameName, address playerAddress);
event LogPlayerReveals(string gameName, address playerAddress, string move);
| 13,337
|
144
|
// IMigratableVault Interface/Enzyme Council <[email protected]>/DO NOT EDIT CONTRACT
|
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
|
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
| 68,427
|
21
|
// Terminate the crowd proposal, send back staked UNI tokens
|
function terminate() external {
require(msg.sender == author, 'CrowdProposal::terminate: only author can terminate');
require(!terminated, 'CrowdProposal::terminate: proposal has been already terminated');
terminated = true;
// Transfer staked UNI tokens from the crowd proposal contract back to the author
IUni(uni).transfer(author, IUni(uni).balanceOf(address(this)));
emit CrowdProposalTerminated(address(this), author);
}
|
function terminate() external {
require(msg.sender == author, 'CrowdProposal::terminate: only author can terminate');
require(!terminated, 'CrowdProposal::terminate: proposal has been already terminated');
terminated = true;
// Transfer staked UNI tokens from the crowd proposal contract back to the author
IUni(uni).transfer(author, IUni(uni).balanceOf(address(this)));
emit CrowdProposalTerminated(address(this), author);
}
| 4,889
|
2
|
// To be raised inside withdrawFeesAndRewards function.localDisputeID The dispute id as in arbitrable contract.round Round code of the appeal. Starts from 0.ruling Indicates the ruling option which got the contribution.contributor Caller of fundAppeal function.reward Total amount of deposits reimbursed plus rewards. This amount will be sent to contributor as an effect of calling withdrawFeesAndRewards function. /
|
event Withdrawal(uint indexed localDisputeID, uint indexed round, uint ruling, address indexed contributor, uint reward);
|
event Withdrawal(uint indexed localDisputeID, uint indexed round, uint ruling, address indexed contributor, uint reward);
| 27,082
|
28
|
// vm.expectRevert(abi.encodeWithSignature("NotStorage(bytes4)", bytes4(keccak256("const()"))));
|
stdstore.target(address(test)).sig("const()").find();
|
stdstore.target(address(test)).sig("const()").find();
| 10,846
|
32
|
// Accept USDT
|
ERC20_USDT(USDTContract).transferFrom(_tokenOwner, address(this), allowanceUsdt);
|
ERC20_USDT(USDTContract).transferFrom(_tokenOwner, address(this), allowanceUsdt);
| 7,708
|
60
|
// Adjust lateness of Project before stage ✅
|
function adjustLatenessBeforeStage(uint256 _projectID) internal {
ProjectManager.Project storage project = projects[_projectID];
uint256 lateness = 0;
// If we are late to start stage by more than 15 minutes, add lateness to all tasks and nextmilestone
if (
block.timestamp >
project.nextMilestone.startStageTimestamp + 15 minutes
) {
lateness =
block.timestamp -
project.nextMilestone.startStageTimestamp;
// Add lateness to all tasks
for (uint256 i = 0; i < project.childTasks.length; i++) {
TaskManager.Task storage task = tasks[project.childTasks[i]];
// Ensure we only update the open tasks which also have workers in for the stage
if (
task.submissionStatus !=
TaskManager.SubmissionStatus.Disputed &&
task.worker != address(0)
) {
task.deadline += lateness; // add lateness to deadline
}
}
// add lateness to nextmilestone
project.nextMilestone.startGateTimestamp += lateness;
project.nextMilestone.startSettledTimestamp += lateness;
}
}
|
function adjustLatenessBeforeStage(uint256 _projectID) internal {
ProjectManager.Project storage project = projects[_projectID];
uint256 lateness = 0;
// If we are late to start stage by more than 15 minutes, add lateness to all tasks and nextmilestone
if (
block.timestamp >
project.nextMilestone.startStageTimestamp + 15 minutes
) {
lateness =
block.timestamp -
project.nextMilestone.startStageTimestamp;
// Add lateness to all tasks
for (uint256 i = 0; i < project.childTasks.length; i++) {
TaskManager.Task storage task = tasks[project.childTasks[i]];
// Ensure we only update the open tasks which also have workers in for the stage
if (
task.submissionStatus !=
TaskManager.SubmissionStatus.Disputed &&
task.worker != address(0)
) {
task.deadline += lateness; // add lateness to deadline
}
}
// add lateness to nextmilestone
project.nextMilestone.startGateTimestamp += lateness;
project.nextMilestone.startSettledTimestamp += lateness;
}
}
| 1,469
|
444
|
// function to initialize the contract
|
function __ERC721WithPermit_init(string memory name_) internal {
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
),
keccak256(bytes(name_)),
keccak256(bytes('1')),
block.chainid,
address(this)
)
);
}
|
function __ERC721WithPermit_init(string memory name_) internal {
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
),
keccak256(bytes(name_)),
keccak256(bytes('1')),
block.chainid,
address(this)
)
);
}
| 44,449
|
221
|
// Token contract checks are in the corresponding TokenNetwork contract
|
token_network = new TokenNetwork(
_token_address,
secret_registry_address,
settlement_timeout_min,
settlement_timeout_max,
controller,
_channel_participant_deposit_limit,
_token_network_deposit_limit
);
|
token_network = new TokenNetwork(
_token_address,
secret_registry_address,
settlement_timeout_min,
settlement_timeout_max,
controller,
_channel_participant_deposit_limit,
_token_network_deposit_limit
);
| 27,845
|
48
|
// check if lending entry has fees
|
uint256 _feesPercent = lentERC721List[tokenAddress][tokenId].platformFeesPercent;
if (feesContractAddress != address(0) && _feesPercent > 0) {
|
uint256 _feesPercent = lentERC721List[tokenAddress][tokenId].platformFeesPercent;
if (feesContractAddress != address(0) && _feesPercent > 0) {
| 19,617
|
6
|
// Emitted when the warmup period is changed/oldVal The old warmup period/newVal The new warmup period
|
event WarmupPeriodSet(uint48 oldVal, uint48 newVal);
|
event WarmupPeriodSet(uint48 oldVal, uint48 newVal);
| 31,200
|
4
|
// Buyer releases balance deposit to seller
|
function releaseBalanceToSeller() internal
|
function releaseBalanceToSeller() internal
| 40,728
|
9
|
// To save cashout date/amount so we can filter by date
|
struct SubPayment {
// The amount of tokens the user cashed out
uint256 amount;
// The date the user performed this cash out
uint256 date;
}
|
struct SubPayment {
// The amount of tokens the user cashed out
uint256 amount;
// The date the user performed this cash out
uint256 date;
}
| 17,082
|
62
|
// ``` As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)and `uint256` (`UintSet`) are supported. [WARNING]====Trying to delete such a structure from storage will likely result in data corruption, rendering the structureunusable. In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using anarray of EnumerableSet.==== /
|
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set)
internal
view
returns (bytes32[] memory)
{
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set)
internal
view
returns (address[] memory)
{
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set)
internal
view
returns (uint256[] memory)
{
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
|
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set)
internal
view
returns (bytes32[] memory)
{
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set)
internal
view
returns (address[] memory)
{
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set)
internal
view
returns (uint256[] memory)
{
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}
| 21,034
|
202
|
// If voter had previously voted, decrease count
|
if (state == VoterState.Yea) {
vote_.yea = vote_.yea.sub(voterStake);
} else if (state == VoterState.Nay) {
|
if (state == VoterState.Yea) {
vote_.yea = vote_.yea.sub(voterStake);
} else if (state == VoterState.Nay) {
| 46,383
|
163
|
// royaltyPayment
|
if (payments[1] > 0) {
SendValueOrEscrow.sendValueOrEscrow(_royaltyPayee, payments[1]);
}
|
if (payments[1] > 0) {
SendValueOrEscrow.sendValueOrEscrow(_royaltyPayee, payments[1]);
}
| 55,212
|
8
|
// Modifiers /
|
modifier isValidListingIndex(uint _index) {
require (_index < listings.length);
_;
}
|
modifier isValidListingIndex(uint _index) {
require (_index < listings.length);
_;
}
| 34,309
|
17
|
// 设置锁
|
function setLock() public returns (bool success) {
require(msg.sender == owner, "not owner");
unLock = !unLock;
success = true;
}
|
function setLock() public returns (bool success) {
require(msg.sender == owner, "not owner");
unLock = !unLock;
success = true;
}
| 31,202
|
23
|
// pragma solidity >0.4.13; /
|
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
//rounds to zero if x*y < WAD / 2
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
|
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
//rounds to zero if x*y < WAD / 2
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
| 49,701
|
42
|
// allow the trove to transfer from the liquidation pool
|
_troves[_token].liquidationPool.approveTrove(troveAddress);
|
_troves[_token].liquidationPool.approveTrove(troveAddress);
| 23,368
|
15
|
// ========== RESTRICTED FUNCTIONS ========== //Not for use in UI. Call once after reward tokens have been received by this contract correctly. This will start the reward duration. It is possible to stake LP tokens ahead of time./reward Quantity of reward to be added the amount that needs to be distributed. Should not be more than what was topped up.
|
function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) {
if (block.timestamp >= periodFinish) {
rewardRate = reward / rewardsDuration;
} else {
uint256 remaining = periodFinish - block.timestamp;
uint256 leftover = remaining * rewardRate;
rewardRate = (reward + leftover) / rewardsDuration;
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
require(rewardRate <= balance / rewardsDuration, "Provided reward too high");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp + rewardsDuration;
emit RewardAdded(reward);
}
|
function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) {
if (block.timestamp >= periodFinish) {
rewardRate = reward / rewardsDuration;
} else {
uint256 remaining = periodFinish - block.timestamp;
uint256 leftover = remaining * rewardRate;
rewardRate = (reward + leftover) / rewardsDuration;
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
require(rewardRate <= balance / rewardsDuration, "Provided reward too high");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp + rewardsDuration;
emit RewardAdded(reward);
}
| 26,181
|
0
|
// slotAttestations[keccak256(blockNumber || addr || slot || slotValue)] = true if and only if it has been checked that:at block number `blockNumber`, the account storage of `addr` has value `slotValue` at slot `slot`
|
mapping(bytes32 => bool) public slotAttestations;
event UpdateAxiomAddress(address newAddress);
event UpdateSnarkVerifierAddress(address newAddress);
constructor(address _axiomAddress, address _verifierAddress) {
axiomAddress = _axiomAddress;
verifierAddress = _verifierAddress;
}
|
mapping(bytes32 => bool) public slotAttestations;
event UpdateAxiomAddress(address newAddress);
event UpdateSnarkVerifierAddress(address newAddress);
constructor(address _axiomAddress, address _verifierAddress) {
axiomAddress = _axiomAddress;
verifierAddress = _verifierAddress;
}
| 20,107
|
9
|
// increase exchange ether amount
|
function donate() public payable{
accumulated = accumulated.add(msg.value);
}
|
function donate() public payable{
accumulated = accumulated.add(msg.value);
}
| 9,703
|
161
|
// Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. startTokenId - the first token id to be transferredquantity - the amount to be transferred Calling conditions: - When `from` and `to` are both non-zero, ``from``'s `tokenId` will betransferred to `to`.- When `from` is zero, `tokenId` will be minted for `to`. /
|
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
|
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
| 45,421
|
68
|
// Returns the tokens and amounts underlying `_user` SHERX balance/_user Account whose underlying SHERX tokens should be queried/ return tokens Array of ERC-20 tokens representing the underlying/ return amounts Corresponding amounts of the underlying tokens
|
function calcUnderlying(address _user)
external
view
returns (IERC20[] memory tokens, uint256[] memory amounts);
|
function calcUnderlying(address _user)
external
view
returns (IERC20[] memory tokens, uint256[] memory amounts);
| 47,911
|
15
|
// Opens short position (for example, swap USDC to ETH, open credit account in ETH, then swap all ETH to USDC)/curvePool Curve pool address/i Index value for the coin to send/j Index value of the coin to receive/amountIn Amount in, if you send ETH as value- it would be taken from msg.value/amountOutMin Minimal amount after first swap before opening account/longParams parameters for long operation/referralCode referral code, it'll be in Action event and in openCreditAccount also
|
function openShortCurve(
address curvePool,
int128 i,
int128 j,
uint256 amountIn,
uint256 amountOutMin,
LongParameters calldata longParams,
uint256 referralCode
|
function openShortCurve(
address curvePool,
int128 i,
int128 j,
uint256 amountIn,
uint256 amountOutMin,
LongParameters calldata longParams,
uint256 referralCode
| 28,626
|
254
|
// The fee is expressed as a percentage. E.g. a value of 40 stands for a 40% fee, so the recipient will be charged for 1.4 times the spent amount.
|
return (gas * gasPrice * (100 + fee)) / 100;
|
return (gas * gasPrice * (100 + fee)) / 100;
| 37,594
|
20
|
// Don't push/pop this all the time, we have just enough space on stack.
|
let mask := 0
|
let mask := 0
| 16,317
|
68
|
// Token contract instance
|
AMOCoin public token;
|
AMOCoin public token;
| 29,231
|
34
|
// slither-disable-next-line incorrect-equality
|
if (sToken.stakePool == 1) {
|
if (sToken.stakePool == 1) {
| 24,667
|
31
|
// Used if an aggregator contract has been proposed. _roundId the round ID to retrieve the round data forreturn roundId is the round ID for which data was retrievedreturn answer is the answer for the given roundreturn startedAt is the timestamp when the round was started.(Only some AggregatorV3Interface implementations return meaningful values)return updatedAt is the timestamp when the round last was updated (i.e.answer was last computed)return answeredInRound is the round ID of the round in which the answerwas computed./
|
function proposedGetRoundData(uint80 _roundId)
public
view
virtual
hasProposal()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
|
function proposedGetRoundData(uint80 _roundId)
public
view
virtual
hasProposal()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
| 8,927
|
16
|
// get faces, verts and colors
|
vars = makeFacesVertsCols(
tokenHash,
tris,
geomVars,
colScheme,
objPosition
);
|
vars = makeFacesVertsCols(
tokenHash,
tris,
geomVars,
colScheme,
objPosition
);
| 31,081
|
40
|
// Allows users to wrap any amount of any ERC-20 token with a 1:1 ratioof corresponding ERC-1155 tokens with native metaTransaction methods. EachERC-20 is assigned an ERC-1155 id for more efficient CALLDATA usage whendoing transfers. /
|
contract MetaERC20Wrapper is ERC1155Meta, ERC1155MintBurn {
// Variables
uint256 internal nTokens = 1; // Number of ERC-20 tokens registered
uint256 constant internal ETH_ID = 0x1; // ID fo tokens representing Ether is 1
address constant internal ETH_ADDRESS = address(0x1); // Address for tokens representing Ether is 0x00...01
mapping (address => uint256) internal addressToID; // Maps the ERC-20 addresses to their metaERC20 id
mapping (uint256 => address) internal IDtoAddress; // Maps the metaERC20 ids to their ERC-20 address
/***********************************|
| Events |
|__________________________________*/
event TokenRegistration(address token_address, uint256 token_id);
/***********************************|
| Constructor |
|__________________________________*/
// Register ETH as ID #1 and address 0x1
constructor() public {
addressToID[ETH_ADDRESS] = ETH_ID;
IDtoAddress[ETH_ID] = ETH_ADDRESS;
}
/***********************************|
| Deposit Functions |
|__________________________________*/
/**
* Fallback function
* @dev Deposit ETH in this contract to receive wrapped ETH
* No parameters provided
*/
receive () external payable {
// Deposit ETH sent with transaction
deposit(ETH_ADDRESS, msg.sender, msg.value);
}
/**
* @dev Deposit ERC20 tokens or ETH in this contract to receive wrapped ERC20s
* @param _token The addess of the token to deposit in this contract
* @param _recipient Address that will receive the ERC-1155 tokens
* @param _value The amount of token to deposit in this contract
* Note: Users must first approve this contract addres on the contract of the ERC20 to be deposited
*/
function deposit(address _token, address _recipient, uint256 _value)
public payable
{
require(_recipient != address(0x0), "MetaERC20Wrapper#deposit: INVALID_RECIPIENT");
// Internal ID of ERC-20 token deposited
uint256 id;
// Deposit ERC-20 tokens or ETH
if (_token != ETH_ADDRESS) {
// Check if transfer passes
require(msg.value == 0, "MetaERC20Wrapper#deposit: NON_NULL_MSG_VALUE");
IERC20(_token).transferFrom(msg.sender, address(this), _value);
require(checkSuccess(), "MetaERC20Wrapper#deposit: TRANSFER_FAILED");
// Load address token ID
uint256 addressId = addressToID[_token];
// Register ID if not already done
if (addressId == 0) {
nTokens += 1; // Increment number of tokens registered
id = nTokens; // id of token is the current # of tokens
IDtoAddress[id] = _token; // Map id to token address
addressToID[_token] = id; // Register token
// Emit registration event
emit TokenRegistration(_token, id);
} else {
id = addressId;
}
} else {
require(_value == msg.value, "MetaERC20Wrapper#deposit: INCORRECT_MSG_VALUE");
id = ETH_ID;
}
// Mint meta tokens
_mint(_recipient, id, _value, "");
}
/***********************************|
| Withdraw Functions |
|__________________________________*/
/**
* @dev Withdraw wrapped ERC20 tokens in this contract to receive the original ERC20s or ETH
* @param _token The addess of the token to withdrww from this contract
* @param _to The address where the withdrawn tokens will go to
* @param _value The amount of tokens to withdraw
*/
function withdraw(address _token, address payable _to, uint256 _value) public {
uint256 tokenID = getTokenID(_token);
_withdraw(msg.sender, _to, tokenID, _value);
}
/**
* @dev Withdraw wrapped ERC20 tokens in this contract to receive the original ERC20s or ETH
* @param _from Address of users sending the Meta tokens
* @param _to The address where the withdrawn tokens will go to
* @param _tokenID The token ID of the ERC-20 token to withdraw from this contract
* @param _value The amount of tokens to withdraw
*/
function _withdraw(
address _from,
address payable _to,
uint256 _tokenID,
uint256 _value)
internal
{
// Burn meta tokens
_burn(_from, _tokenID, _value);
// Withdraw ERC-20 tokens or ETH
if (_tokenID != ETH_ID) {
address token = IDtoAddress[_tokenID];
IERC20(token).transfer(_to, _value);
require(checkSuccess(), "MetaERC20Wrapper#withdraw: TRANSFER_FAILED");
} else {
require(_to != address(0), "MetaERC20Wrapper#withdraw: INVALID_RECIPIENT");
(bool success, ) = _to.call{value: _value}("");
require(success, "MetaERC20Wrapper#withdraw: TRANSFER_FAILED");
}
}
/**
* @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _value The amount of tokens being transferred
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(address, address payable _from, uint256 _id, uint256 _value, bytes memory)
public returns(bytes4)
{
// Only ERC-1155 from this contract are valid
require(msg.sender == address(this), "MetaERC20Wrapper#onERC1155Received: INVALID_ERC1155_RECEIVED");
getIdAddress(_id); // Checks if id is registered
// Tokens are received, hence need to burn them here
_withdraw(address(this), _from, _id, _value);
return ERC1155_RECEIVED_VALUE;
}
/**
* @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _values An array containing amounts of each token being transferred
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(address, address payable _from, uint256[] memory _ids, uint256[] memory _values, bytes memory)
public returns(bytes4)
{
// Only ERC-1155 from this contract are valid
require(msg.sender == address(this), "MetaERC20Wrapper#onERC1155BatchReceived: INVALID_ERC1155_RECEIVED");
// Withdraw all tokens
for ( uint256 i = 0; i < _ids.length; i++) {
// Checks if id is registered
getIdAddress(_ids[i]);
// Tokens are received, hence need to burn them here
_withdraw(address(this), _from, _ids[i], _values[i]);
}
return ERC1155_BATCH_RECEIVED_VALUE;
}
/**
* @notice Return the Meta-ERC20 token ID for the given ERC-20 token address
* @param _token ERC-20 token address to get the corresponding Meta-ERC20 token ID
* @return tokenID Meta-ERC20 token ID
*/
function getTokenID(address _token) public view returns (uint256 tokenID) {
tokenID = addressToID[_token];
require(tokenID != 0, "MetaERC20Wrapper#getTokenID: UNREGISTERED_TOKEN");
return tokenID;
}
/**
* @notice Return the ERC-20 token address for the given Meta-ERC20 token ID
* @param _id Meta-ERC20 token ID to get the corresponding ERC-20 token address
* @return token ERC-20 token address
*/
function getIdAddress(uint256 _id) public view returns (address token) {
token = IDtoAddress[_id];
require(token != address(0x0), "MetaERC20Wrapper#getIdAddress: UNREGISTERED_TOKEN");
return token;
}
/**
* @notice Returns number of tokens currently registered
*/
function getNTokens() external view returns (uint256) {
return nTokens;
}
/***********************************|
| Helper Functions |
|__________________________________*/
/**
* Checks the return value of the previous function up to 32 bytes. Returns true if the previous
* function returned 0 bytes or 32 bytes that are not all-zero.
* Code taken from: https://github.com/dydxprotocol/solo/blob/10baf8e4c3fb9db4d0919043d3e6fdd6ba834046/contracts/protocol/lib/Token.sol
*/
function checkSuccess()
private pure
returns (bool)
{
uint256 returnValue = 0;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
// check number of bytes returned from last function call
switch returndatasize()
// no bytes returned: assume success
case 0x0 {
returnValue := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// copy 32 bytes into scratch space
returndatacopy(0x0, 0x0, 0x20)
// load those bytes into returnValue
returnValue := mload(0x0)
}
// not sure what was returned: dont mark as success
default { }
}
return returnValue != 0;
}
/**
* @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types.
* @param interfaceID The ERC-165 interface ID that is queried for support.s
* @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface.
* This function MUST NOT consume more thsan 5,000 gas.
* @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported.
*/
function supportsInterface(bytes4 interfaceID) external override pure returns (bool) {
return interfaceID == type(IERC165).interfaceId ||
interfaceID == type(IERC1155).interfaceId ||
interfaceID == type(IERC1155TokenReceiver).interfaceId;
}
}
|
contract MetaERC20Wrapper is ERC1155Meta, ERC1155MintBurn {
// Variables
uint256 internal nTokens = 1; // Number of ERC-20 tokens registered
uint256 constant internal ETH_ID = 0x1; // ID fo tokens representing Ether is 1
address constant internal ETH_ADDRESS = address(0x1); // Address for tokens representing Ether is 0x00...01
mapping (address => uint256) internal addressToID; // Maps the ERC-20 addresses to their metaERC20 id
mapping (uint256 => address) internal IDtoAddress; // Maps the metaERC20 ids to their ERC-20 address
/***********************************|
| Events |
|__________________________________*/
event TokenRegistration(address token_address, uint256 token_id);
/***********************************|
| Constructor |
|__________________________________*/
// Register ETH as ID #1 and address 0x1
constructor() public {
addressToID[ETH_ADDRESS] = ETH_ID;
IDtoAddress[ETH_ID] = ETH_ADDRESS;
}
/***********************************|
| Deposit Functions |
|__________________________________*/
/**
* Fallback function
* @dev Deposit ETH in this contract to receive wrapped ETH
* No parameters provided
*/
receive () external payable {
// Deposit ETH sent with transaction
deposit(ETH_ADDRESS, msg.sender, msg.value);
}
/**
* @dev Deposit ERC20 tokens or ETH in this contract to receive wrapped ERC20s
* @param _token The addess of the token to deposit in this contract
* @param _recipient Address that will receive the ERC-1155 tokens
* @param _value The amount of token to deposit in this contract
* Note: Users must first approve this contract addres on the contract of the ERC20 to be deposited
*/
function deposit(address _token, address _recipient, uint256 _value)
public payable
{
require(_recipient != address(0x0), "MetaERC20Wrapper#deposit: INVALID_RECIPIENT");
// Internal ID of ERC-20 token deposited
uint256 id;
// Deposit ERC-20 tokens or ETH
if (_token != ETH_ADDRESS) {
// Check if transfer passes
require(msg.value == 0, "MetaERC20Wrapper#deposit: NON_NULL_MSG_VALUE");
IERC20(_token).transferFrom(msg.sender, address(this), _value);
require(checkSuccess(), "MetaERC20Wrapper#deposit: TRANSFER_FAILED");
// Load address token ID
uint256 addressId = addressToID[_token];
// Register ID if not already done
if (addressId == 0) {
nTokens += 1; // Increment number of tokens registered
id = nTokens; // id of token is the current # of tokens
IDtoAddress[id] = _token; // Map id to token address
addressToID[_token] = id; // Register token
// Emit registration event
emit TokenRegistration(_token, id);
} else {
id = addressId;
}
} else {
require(_value == msg.value, "MetaERC20Wrapper#deposit: INCORRECT_MSG_VALUE");
id = ETH_ID;
}
// Mint meta tokens
_mint(_recipient, id, _value, "");
}
/***********************************|
| Withdraw Functions |
|__________________________________*/
/**
* @dev Withdraw wrapped ERC20 tokens in this contract to receive the original ERC20s or ETH
* @param _token The addess of the token to withdrww from this contract
* @param _to The address where the withdrawn tokens will go to
* @param _value The amount of tokens to withdraw
*/
function withdraw(address _token, address payable _to, uint256 _value) public {
uint256 tokenID = getTokenID(_token);
_withdraw(msg.sender, _to, tokenID, _value);
}
/**
* @dev Withdraw wrapped ERC20 tokens in this contract to receive the original ERC20s or ETH
* @param _from Address of users sending the Meta tokens
* @param _to The address where the withdrawn tokens will go to
* @param _tokenID The token ID of the ERC-20 token to withdraw from this contract
* @param _value The amount of tokens to withdraw
*/
function _withdraw(
address _from,
address payable _to,
uint256 _tokenID,
uint256 _value)
internal
{
// Burn meta tokens
_burn(_from, _tokenID, _value);
// Withdraw ERC-20 tokens or ETH
if (_tokenID != ETH_ID) {
address token = IDtoAddress[_tokenID];
IERC20(token).transfer(_to, _value);
require(checkSuccess(), "MetaERC20Wrapper#withdraw: TRANSFER_FAILED");
} else {
require(_to != address(0), "MetaERC20Wrapper#withdraw: INVALID_RECIPIENT");
(bool success, ) = _to.call{value: _value}("");
require(success, "MetaERC20Wrapper#withdraw: TRANSFER_FAILED");
}
}
/**
* @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _value The amount of tokens being transferred
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(address, address payable _from, uint256 _id, uint256 _value, bytes memory)
public returns(bytes4)
{
// Only ERC-1155 from this contract are valid
require(msg.sender == address(this), "MetaERC20Wrapper#onERC1155Received: INVALID_ERC1155_RECEIVED");
getIdAddress(_id); // Checks if id is registered
// Tokens are received, hence need to burn them here
_withdraw(address(this), _from, _id, _value);
return ERC1155_RECEIVED_VALUE;
}
/**
* @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _values An array containing amounts of each token being transferred
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(address, address payable _from, uint256[] memory _ids, uint256[] memory _values, bytes memory)
public returns(bytes4)
{
// Only ERC-1155 from this contract are valid
require(msg.sender == address(this), "MetaERC20Wrapper#onERC1155BatchReceived: INVALID_ERC1155_RECEIVED");
// Withdraw all tokens
for ( uint256 i = 0; i < _ids.length; i++) {
// Checks if id is registered
getIdAddress(_ids[i]);
// Tokens are received, hence need to burn them here
_withdraw(address(this), _from, _ids[i], _values[i]);
}
return ERC1155_BATCH_RECEIVED_VALUE;
}
/**
* @notice Return the Meta-ERC20 token ID for the given ERC-20 token address
* @param _token ERC-20 token address to get the corresponding Meta-ERC20 token ID
* @return tokenID Meta-ERC20 token ID
*/
function getTokenID(address _token) public view returns (uint256 tokenID) {
tokenID = addressToID[_token];
require(tokenID != 0, "MetaERC20Wrapper#getTokenID: UNREGISTERED_TOKEN");
return tokenID;
}
/**
* @notice Return the ERC-20 token address for the given Meta-ERC20 token ID
* @param _id Meta-ERC20 token ID to get the corresponding ERC-20 token address
* @return token ERC-20 token address
*/
function getIdAddress(uint256 _id) public view returns (address token) {
token = IDtoAddress[_id];
require(token != address(0x0), "MetaERC20Wrapper#getIdAddress: UNREGISTERED_TOKEN");
return token;
}
/**
* @notice Returns number of tokens currently registered
*/
function getNTokens() external view returns (uint256) {
return nTokens;
}
/***********************************|
| Helper Functions |
|__________________________________*/
/**
* Checks the return value of the previous function up to 32 bytes. Returns true if the previous
* function returned 0 bytes or 32 bytes that are not all-zero.
* Code taken from: https://github.com/dydxprotocol/solo/blob/10baf8e4c3fb9db4d0919043d3e6fdd6ba834046/contracts/protocol/lib/Token.sol
*/
function checkSuccess()
private pure
returns (bool)
{
uint256 returnValue = 0;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
// check number of bytes returned from last function call
switch returndatasize()
// no bytes returned: assume success
case 0x0 {
returnValue := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// copy 32 bytes into scratch space
returndatacopy(0x0, 0x0, 0x20)
// load those bytes into returnValue
returnValue := mload(0x0)
}
// not sure what was returned: dont mark as success
default { }
}
return returnValue != 0;
}
/**
* @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types.
* @param interfaceID The ERC-165 interface ID that is queried for support.s
* @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface.
* This function MUST NOT consume more thsan 5,000 gas.
* @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported.
*/
function supportsInterface(bytes4 interfaceID) external override pure returns (bool) {
return interfaceID == type(IERC165).interfaceId ||
interfaceID == type(IERC1155).interfaceId ||
interfaceID == type(IERC1155TokenReceiver).interfaceId;
}
}
| 4,995
|
97
|
// The cap of this presale contract in wei // Server holds the private key to this address to decide if the AML payload is valid or not. // A new server-side signer key was set to be effective // An user made a prepurchase through KYC'ed interface. The money has been moved to the token sale multisig wallet. The buyer will receive their tokens in an airdrop after the token sale is over. // The owner changes the presale ETH cap during the sale //Constructor. Presale does not know about token or pricing strategy, as they will be only available
|
function KYCPresale(address _multisigWallet, uint _start, uint _end, uint _saleWeiCap) CrowdsaleBase(FractionalERC20(address(1)), PricingStrategy(address(0)), _multisigWallet, _start, _end, 0) {
saleWeiCap = _saleWeiCap;
}
|
function KYCPresale(address _multisigWallet, uint _start, uint _end, uint _saleWeiCap) CrowdsaleBase(FractionalERC20(address(1)), PricingStrategy(address(0)), _multisigWallet, _start, _end, 0) {
saleWeiCap = _saleWeiCap;
}
| 35,821
|
8
|
// check if a pool with this gauge already exists
|
bool gaugeExists = IPools(pools).gaugeMap(_gauge);
require(!gaugeExists, "already registered gauge");
|
bool gaugeExists = IPools(pools).gaugeMap(_gauge);
require(!gaugeExists, "already registered gauge");
| 15,900
|
9
|
// Info: current game
|
bool public gameActive;
Coordinates public devCoordinates;
uint256 private currentGameNumber = 0;
mapping(uint256 => mapping(address => address[])) public rewardsUsage;
uint256 public accumulatedTokens;
|
bool public gameActive;
Coordinates public devCoordinates;
uint256 private currentGameNumber = 0;
mapping(uint256 => mapping(address => address[])) public rewardsUsage;
uint256 public accumulatedTokens;
| 26,522
|
50
|
// Constructor; must supply bankroll address
|
constructor(address BankrollAddress)
public
|
constructor(address BankrollAddress)
public
| 69,956
|
315
|
// solhint-disable not-rely-on-time
|
_reportResult(_queryId, block.timestamp, _drTxHash, _cborBytes);
|
_reportResult(_queryId, block.timestamp, _drTxHash, _cborBytes);
| 22,495
|
49
|
// Updates reward variables `lastRewardedTimestampHour`, `accumulatedRewardsPerShare` and `lastRewardsRangeIndex`for a given pool. _poolId Available pool values 0-3 /
|
function updatePool(uint256 _poolId) public {
Pool storage pool = pools[_poolId];
if (block.timestamp < pool.timeRanges[0].startTimestampHour) return;
if (block.timestamp <= pool.lastRewardedTimestampHour + SECONDS_PER_HOUR) return;
uint48 lastTimestampHour = pool.timeRanges[pool.timeRanges.length-1].endTimestampHour;
uint48 previousTimestampHour = getPreviousTimestampHour().toUint48();
if (pool.stakedAmount == 0) {
pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour;
return;
}
(uint256 rewards, uint256 index) = rewardsBy(_poolId, pool.lastRewardedTimestampHour, previousTimestampHour);
if (pool.lastRewardsRangeIndex != index) {
pool.lastRewardsRangeIndex = index.toUint16();
}
pool.accumulatedRewardsPerShare = (pool.accumulatedRewardsPerShare + (rewards * NFTE_TOKEN_PRECISION) / pool.stakedAmount).toUint96();
pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour;
emit UpdatePool(_poolId, pool.lastRewardedTimestampHour, pool.stakedAmount, pool.accumulatedRewardsPerShare);
}
|
function updatePool(uint256 _poolId) public {
Pool storage pool = pools[_poolId];
if (block.timestamp < pool.timeRanges[0].startTimestampHour) return;
if (block.timestamp <= pool.lastRewardedTimestampHour + SECONDS_PER_HOUR) return;
uint48 lastTimestampHour = pool.timeRanges[pool.timeRanges.length-1].endTimestampHour;
uint48 previousTimestampHour = getPreviousTimestampHour().toUint48();
if (pool.stakedAmount == 0) {
pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour;
return;
}
(uint256 rewards, uint256 index) = rewardsBy(_poolId, pool.lastRewardedTimestampHour, previousTimestampHour);
if (pool.lastRewardsRangeIndex != index) {
pool.lastRewardsRangeIndex = index.toUint16();
}
pool.accumulatedRewardsPerShare = (pool.accumulatedRewardsPerShare + (rewards * NFTE_TOKEN_PRECISION) / pool.stakedAmount).toUint96();
pool.lastRewardedTimestampHour = previousTimestampHour > lastTimestampHour ? lastTimestampHour : previousTimestampHour;
emit UpdatePool(_poolId, pool.lastRewardedTimestampHour, pool.stakedAmount, pool.accumulatedRewardsPerShare);
}
| 18,472
|
152
|
// `updateValueAtNow` used to update the `balances` map and the/`totalSupplyHistory`/checkpoints The history of data being updated/_value The new number of tokens
|
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
|
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
| 45,874
|
24
|
// swap calls are restricted only to HolyHand transfer proxy, which is set using this method
|
function setTransferProxy(address _transferProxyAddress) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
transferProxyAddress = _transferProxyAddress;
}
|
function setTransferProxy(address _transferProxyAddress) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
transferProxyAddress = _transferProxyAddress;
}
| 29,557
|
5
|
// Sets `reward rate`. Returns a boolean value indicating whether the operation succeeded. /
|
function setRewardRate(uint256 rewardRate) external returns (bool success);
|
function setRewardRate(uint256 rewardRate) external returns (bool success);
| 31,899
|
39
|
// pragma solidity 0.6.7; / computes square roots using the babylonian method https:en.wikipedia.org/wiki/Methods_of_computing_square_rootsBabylonian_method
|
contract BabylonianMath {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
|
contract BabylonianMath {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
| 32,142
|
44
|
// Create an new Identity for the transaction sender./Sets the msg.sender as the only associatedAddress./recoveryAddress A recovery address to set for the new Identity./providers A list of providers to set for the new Identity./resolvers A list of resolvers to set for the new Identity./ return The EIN of the new Identity.
|
function createIdentity(address recoveryAddress, address[] memory providers, address[] memory resolvers)
public returns (uint ein)
|
function createIdentity(address recoveryAddress, address[] memory providers, address[] memory resolvers)
public returns (uint ein)
| 51,072
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.