comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/ | function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
l... | 0.6.6 |
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buf... | function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, (len + off) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
... | 0.6.6 |
/**
* @notice Initializes a Chainlink request
* @dev Sets the ID, callback address, and callback function signature on the request
* @param self The uninitialized request
* @param _id The Job Specification ID
* @param _callbackAddress The callback address
* @param _callbackFunction The callback function sig... | function initialize(
Request memory self,
bytes32 _id,
address _callbackAddress,
bytes4 _callbackFunction
) internal pure returns (Chainlink.Request memory) {
Buffer_Chainlink.init(self.buf, defaultBufferSize);
self.id = _id;
self.callbackAddress = _callbackAddress;
self.callb... | 0.6.6 |
/**
* @notice Creates a Chainlink request to the specified oracle address
* @dev Generates and stores a request ID, increments the local nonce, and uses `transferAndCall` to
* send LINK which creates a request on the target oracle contract.
* Emits ChainlinkRequested event.
* @param _oracle The address of the... | function sendChainlinkRequestTo(address _oracle, Chainlink.Request memory _req, uint256 _payment)
internal
returns (bytes32 requestId)
{
requestId = keccak256(abi.encodePacked(this, requestCount));
_req.nonce = requestCount;
pendingRequests[requestId] = _oracle;
emit ChainlinkRequested(... | 0.6.6 |
/**
* @notice Encodes the request to be sent to the oracle contract
* @dev The Chainlink node expects values to be in order for the request to be picked up. Order of types
* will be validated in the oracle contract.
* @param _req The initialized Chainlink Request
* @return The bytes payload for the `transferA... | function encodeRequest(Chainlink.Request memory _req)
private
view
returns (bytes memory)
{
return abi.encodeWithSelector(
oracle.oracleRequest.selector,
SENDER_OVERRIDE, // Sender value - overridden by onTokenTransfer by the requesting contract's address
AMOUNT_OVERRIDE, // ... | 0.6.6 |
/**
* @dev This function can be executed by any user out there to calculate the amount of UNP they can claim.
* The function creates a Chainlink Request to get a single user's total claimable tokens (tokens_to_claim) using the BASE_URL + the user's address
*
* Example URL: https://BASE_URL/... | function getTokensToClaimByAddress() public payable {
require(msg.value >= gasCosts, "You have to send more eth to cover gas costs");
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(jobId), address(this), this.setTokensToClaim.selector);
req.add("get", BASE_URL);
req.add("extPath", addr... | 0.6.6 |
/**
* @dev Convertes a String to Bytes32
* @param source source string to be converted
*/ | function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {// solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
} | 0.6.6 |
/**
* @dev Convertes an address to string
* @param x address you want to converte
*/ | function addressToString(address x) internal pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
byte b = byte(uint8(uint(x) / (2 ** (8 * (19 - i)))));
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[2 * i] = char(hi);
s[2 ... | 0.6.6 |
// =============
// ==================
// Crowdsale Stage Management
// =========================================================
// Change Crowdsale Stage. Available Options: PrivateSale, ICOFirstStage, ICOSecondStage, ICOThirdStage | function setCrowdsaleStage(uint value) public onlyOwner {
CrowdsaleStage _stage;
if (uint(CrowdsaleStage.PrivateSale) == value) {
_stage = CrowdsaleStage.PrivateSale;
} else if (uint(CrowdsaleStage.ICOFirstStage) == value) {
_stage = CrowdsaleStage.ICOFirstStage;
} else if ... | 0.4.25 |
// ===========================
// Final distribution and crowdsale finalization
// ==================================================================== | function finish(address _teamFund, address _reserveFund, address _bountyFund, address _advisoryFund) public onlyOwner {
require(!isFinalized);
uint256 alreadyMinted = token.totalSupply();
uint256 tokensForTeam = alreadyMinted.mul(15).div(100);
uint256 tokensForBounty = alreadyMinted.mul(2).d... | 0.4.25 |
/**
* @dev Set the fee divisor for the specified token
*/ | function setFeeDivisor(address token, uint256 _feeDivisor) external override returns (uint256 oldDivisor) {
require(operator == msg.sender, "UNAUTHORIZED");
require(_feeDivisor != 0, "DIVISIONBYZERO");
oldDivisor = feeDivisors[token];
feeDivisors[token] = _feeDivisor;
emit FeeDiv... | 0.7.3 |
//minting a new NFT | function mint(uint number) payable public {
require(saleState_ == State.OpenSale, 'Sale is not open yet!');
require(totalSupply() + number <= maxTokens, 'No more NFTs left to mint!');
require(msg.value >= mintCost() * number, 'Insufficient Funds, Check current price to Mint');
requir... | 0.8.7 |
//to see the price of minting | function mintCost() public view returns(uint) {
if (saleState_ == State.NoSale) {
return mintCost_;
}
else {
uint incrementPeriods = (block.timestamp - saleLaunchTime) / 300;
if (mintCost_ <= (incrementPeriods * 0.00017361 ether)) {
retu... | 0.8.7 |
/// @dev Accepts ether and creates new edan tokens. | function createTokens() payable external {
if (isFinalized) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingEndBlock) throw;
if (msg.value == 0) throw;
uint256 tokens = safeMult(msg.value, ExchangeRate); // check that we're not over totals
uint25... | 0.4.12 |
/// @dev Ends the funding period and sends the ETH home | function finalize() external {
if (isFinalized) throw;
if (msg.sender != ethFundDeposit) throw; // locks finalize to the ultimate ETH owner
if(totalSupply < tokenCreationMin) throw; // have to sell minimum to move to operational
if(block.number <= fundingEndBlock && totalSupply != token... | 0.4.12 |
/// @dev Allows contributors to recover their ether in the case of a failed funding campaign. | function refund() external {
if(isFinalized) throw; // prevents refund if operational
if (block.number <= fundingEndBlock) throw; // prevents refund until sale period is over
if(totalSupply >= tokenCreationMin) throw; // no refunds if we sold enough
if(msg.sender == ed... | 0.4.12 |
// Creates a new token type and assings _initialSupply to minter | function _create(uint256 _initialSupply, address _to, string memory _name) internal returns (uint256 _id) {
_id = ++nonce;
balances[_id][_to] = _initialSupply;
_totalSupplies[_id] = _initialSupply;
// Transfer event with mint semantic
emit TransferSingle(msg.sender, addr... | 0.5.2 |
/**
@notice This function is used to invest in given balancer pool using ETH/ERC20 Tokens
@param _FromTokenContractAddress The token used for investment (address(0x00) if ether)
@param _ToBalancerPoolAddress The address of balancer pool
@param _toTokenContractAddress The token with which we are adding liquidity
@p... | function ZapIn(
address _FromTokenContractAddress,
address _ToBalancerPoolAddress,
address _toTokenContractAddress,
uint256 _amount,
uint256 _minPoolTokens,
address _swapTarget,
bytes calldata swapData,
address affiliate
) external payable stopInEmerge... | 0.8.4 |
// Polka Party Team - always failing *Removed Require* Better solution is needed
// uniswap - 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 ... | function notifyRewardAmount(uint256 reward) external onlyRewardsDistribution setReward(address(0)) {
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
// base instructions
lastUpdateTime = block.timestamp;
periodFinish = block.t... | 0.5.17 |
// Retrieve the encrypted key to decrypt a resource referenced by an accepted proposal. | function getEncryptedResourceDecryptionKey(uint256 proposalId, uint256 resourceId) external view returns (bytes) {
require(proposalId < proposalCount);
require(ProposalState.AcceptedByResourceSetCreator == statesByProposalId[proposalId]);
require(resourceId < resourceCount);
uint25... | 0.4.19 |
// This function moves a proposal to a final state of `RejectedByResourceSetCreator' and sends tokens to the
// destinations described by the proposal's transfers.
//
// The caller should encrypt each decryption key corresponding
// to each resource in the proposal's resource set first with the public key of the propos... | function acceptProposal(
uint256 proposalId,
bytes concatenatedResourceDecryptionKeys,
uint256[] concatenatedResourceDecryptionKeyLengths
) external
{
require(proposalId < proposalCount);
require(ProposalState.Pending == statesByProposalId[proposalId]);
... | 0.4.19 |
// For marketing etc. | function devMint(uint256 quantity) external onlyOwner {
require(totalSupply() + quantity <= devMintQty, "too many already minted before dev mint");
require(quantity % maxBatchSize == 0, "can only mint a multiple of the maxBatchSize");
uint256 numChunks = quantity / maxBatchSize;
for (uin... | 0.8.11 |
// Internal function transfer can only be called by this contract
// Emit Transfer Event event | function _transfer(address _from, address _to, uint256 _value) internal {
// Ensure sending is to valid address! 0x0 address cane be used to burn()
require(_to != address(0));
balanceOf[_from] = balanceOf[_from] - (_value);
balanceOf[_to] = balanceOf[_to] + (_value);
emit T... | 0.8.9 |
/**
* @dev Calculate amount of vested tokens at a specific time
* @param tokens uint256 The amount of tokens granted
* @param time uint64 The time to be checked
* @param start uint64 The time representing the beginning of the grant
* @param cliff uint64 The cliff period, the period before nothing can be paid... | function calculateVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vesting) public constant returns (uint256)
{
// Shortcuts for before cliff and after vesting cases.
if (time < cliff) return 0;
if (time >= vesting) return tokens;
// Interpolate a... | 0.4.16 |
// @notice Takes order from 0x and returns bool indicating if it is successful
// @param _addresses [exchange, src, dst]
// @param _data Data to send with call
// @param _value Value to send with call
// @param _amount Amount being sold | function takeOrder(address[3] memory _addresses, bytes memory _data, uint _value, uint _amount) private returns(bool, uint, uint) {
bool success;
(success, ) = _addresses[0].call.value(_value)(_data);
uint tokensLeft = _amount;
uint tokensReturned = 0;
if (success){
... | 0.5.7 |
/// @notice Returns the best estimated price from 2 exchanges
/// @param _amount Amount of source tokens you want to exchange
/// @param _srcToken Address of the source token
/// @param _destToken Address of the destination token
/// @return (address, uint) The address of the best exchange and the exchange price | function getBestPrice(uint _amount, address _srcToken, address _destToken, uint _exchangeType) public returns (address, uint) {
uint expectedRateKyber;
uint expectedRateUniswap;
uint expectedRateOasis;
if (_exchangeType == 1) {
return (OASIS_WRAPPER, getExpectedRate(OASIS_W... | 0.5.7 |
/// @notice Takes a feePercentage and sends it to wallet
/// @param _amount Dai amount of the whole trade
/// @return feeAmount Amount in Dai owner earned on the fee | function takeFee(uint _amount, address _token) internal returns (uint feeAmount) {
uint fee = SERVICE_FEE;
if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) {
fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender);
}
if (fee == 0) {
feeAmount ... | 0.5.7 |
// ------------------------------------------------------------------------
// Function to mint tokens within the cap limit
// @param _to The address that will receive the minted tokens.
// @param _amount The amount of tokens to mint.
// @return A boolean that indicates if the operation was successful.
// -------------... | function mint(address _to, uint256 _amount) hasMintPermission canMint public returns (bool) {
require(_amount <= batchlimits);
require(_totalSupply.add(_amount) <= cap);
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Tran... | 0.4.24 |
// @dev 1) Ends the previous auction if it hasn't been ended already
// 2) Mints a new Mxtter Token
// 3) Create a new zora auction with the minted token
// 4) Creates a min bid on the auction to kick off the timer
// 5) Updates curent auction ID | function newAuction() external onlyOwner {
// Will revert if auction was already ended by someone else
try auctionHouse.endAuction(curAuctionId) {
emit Log("ended auction", curAuctionId);
} catch {
emit Log("auction already ended", curAuctionId);
}
uint25... | 0.8.4 |
/// @inheritdoc IERC2981Royalties | function royaltyInfo(
uint256,
uint256 _value
)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalties = _royalties;
receiver = royalties.recipient;
royaltyAmount = (_value * royalties.amount) / 10000;
} | 0.8.9 |
// claim for hodl | function claimDAO() public {
require(
rally.balanceOf(msg.sender) >= rallyBalance ||
bank.balanceOf(msg.sender) >= bankBalance ||
fwb.balanceOf(msg.sender) >= fwbBalance ||
ff.balanceOf(msg.sender) >= ffBalance,
"low balance"
);
requir... | 0.8.4 |
// mintPreSale allows for minting by allowed addresses during the pre-sale. | function mintPreSale(
uint8 quantity,
bytes32[] calldata merkleProof)
external
payable
nonReentrant
preSaleActive
canMintTunes(quantity)
isCorrectPayment(SALE_PRICE, quantity)
isValidMerkleProof(merkleProof, preSaleMerkleRoot)
{
... | 0.8.7 |
/**
* @dev Take orders by their orderID.
* @param orderIDs Array of order ids to be taken.
* @param buyers Array of buyers.
* @param quantity Array of quantity per purchase.
* @param timeOutBlockNumber Time-out block number.
*/ | function takeOrders(
bytes32[] calldata orderIDs,
address[] calldata buyers,
uint256[] calldata quantity,
uint256 timeOutBlockNumber
) external whenNotPaused checkBatchLength(orderIDs.length) checkTimeOut(timeOutBlockNumber) {
require(
orderIDs.length == buyers.le... | 0.5.12 |
/**
* @dev Let investor make an order, providing the approval is done beforehand.
* @param isComplete If this order can be filled partially (by default), or can only been taken as a whole.
* @param sellToken Address of the token to be sold in this order.
* @param sellAmount Total amount of token that is planned to ... | function makeOrder(
bytes32 orderID,
address specificTaker, // if no one, just pass address(0)
address seller,
bool isComplete,
ISygnumToken sellToken,
uint256 sellAmount,
ISygnumToken buyToken,
uint256 buyAmount,
uint256 timeOutBlockNumber
)
... | 0.5.12 |
/**
* @dev Cancel an order by its maker or a trader.
* @param orderID Order ID.
*/ | function cancelOrder(bytes32 orderID) public {
require(orders.exists(orderID), "Exchange: order ID does not exist");
Order memory theOrder = order[orderID];
require(
isTrader(msg.sender) || (isNotPaused() && theOrder.maker == msg.sender),
"Exchange: not eligible to cancel... | 0.5.12 |
/**
* @dev Internal take order
* @param orderID Order ID.
* @param buyer Address of a seller, if applies.
* @param quantity Amount to purchase.
*/ | function _takeOrder(
bytes32 orderID,
address buyer,
uint256 quantity
) private {
require(orders.exists(orderID), "Exchange: order ID does not exist");
require(buyer != address(0), "Exchange: buyer cannot be set to an empty address");
require(quantity > 0, "Exchange: ... | 0.5.12 |
/**
* @dev Internal make order
* @param orderID Order ID.
* @param specificTaker Address of a taker, if applies.
* @param isComplete If this order can be filled partially, or can only been taken as a whole.
* @param sellToken Address of the token to be sold in this order.
* @param sellAmount Total amount of token... | function _makeOrder(
bytes32 orderID,
address specificTaker,
address seller,
bool isComplete,
ISygnumToken sellToken,
uint256 sellAmount,
ISygnumToken buyToken,
uint256 buyAmount
) private {
require(!orders.exists(orderID), "Exchange: order id ... | 0.5.12 |
/**
* @dev Function to grant the amount of tokens that will be vested later.
* @param _to The address which will own the tokens.
* @param _amount The amount of tokens that will be vested later.
* @param _start Token timestamp start.
* @param _cliff Token timestamp release start.
* @param _vesting Token time... | function grantToken(
address _to,
uint256 _amount,
uint256 _start,
uint256 _cliff,
uint256 _vesting
)
public
returns (bool success)
{
require(_to != address(0));
require(_amount <= balances[msg.sender], "Not enough balance to gra... | 0.4.24 |
/**
* @dev Function to calculate the amount of tokens that can be vested at this moment.
* @param _to The address which will own the tokens.
* @return amount - A uint256 specifying the amount of tokens available to be vested at this moment.
* @return vestedMonths - A uint256 specifying the number of the vested ... | function calcVestableToken(address _to)
internal view
returns (uint256 amount, uint256 vestedMonths, uint256 curTime)
{
uint256 vestTotalMonths;
uint256 vestedAmount;
uint256 vestPart;
amount = 0;
vestedMonths = 0;
curTime = now;
... | 0.4.24 |
/**
* @dev Function to redeem tokens that can be vested at this moment.
* @param _to The address which will own the tokens.
*/ | function redeemVestableToken(address _to)
public
returns (bool success)
{
require(_to != address(0));
require(timeLocks[_to].amount > 0, "Nothing was granted to this address!");
require(timeLocks[_to].vestedAmount < timeLocks[_to].amount, "All tokens were vested!");
... | 0.4.24 |
/**
* @dev Function to return granted token to the initial sender.
* @param _amount - A uint256 specifying the amount of tokens to be returned.
*/ | function returnGrantedToken(uint256 _amount)
public
returns (bool success)
{
address to = timeLocks[msg.sender].from;
require(to != address(0));
require(_amount > 0, "Nothing to transfer.");
require(timeLocks[msg.sender].amount > 0, "Nothing to return.");
... | 0.4.24 |
/**
* @notice Mints monster tokens during presale, optionally with discounts
* @param _numberOfTokens Number of tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
* @param _whitelistedTokens Account's total number of whitelisted tokens
* @param _proof Merkle proof to be veri... | function mintTokensPresale(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount,
uint256 _whitelistedTokens,
bytes32[] calldata _proof
)
external
payable
{
require(
publicSaleOpenedEarly == false,
"Presale has en... | 0.8.9 |
/**
* @notice Mints monsters during public sale, optionally with discounts
* @param _numberOfTokens Number of monster tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
*/ | function mintTokensPublicSale(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount
)
external
payable
{
require(
publicSaleOpened() == true,
"Public sale has not started"
);
require(
belowMaximum(m... | 0.8.9 |
/**
* @notice Modifies the prices in case of major ETH price changes
* @param _tokenPrice The new default token price
* @param _discountPrice The new discount token price
*/ | function updateTokenPrices(
uint256 _tokenPrice,
uint256 _discountPrice
)
external
onlyOwner
{
require(
_tokenPrice >= _discountPrice,
"discountPrice cannot be larger"
);
require(
saleIsActive == false,
... | 0.8.9 |
/**
* @notice Checks which Satoshibles can still be used for a discounted mint
* @dev Uses bitwise operators to find the bit representing each Satoshible
* @param _satIds Array of original Satoshible token IDs
* @return Token ID for each of the available _satIds, zero otherwise
*/ | function satsAvailableForDiscountMint(
uint256[] calldata _satIds
)
external
view
returns (uint256[] memory)
{
uint256[] memory satsAvailable = new uint256[](_satIds.length);
unchecked {
for (uint256 i = 0; i < _satIds.length; i++) {
... | 0.8.9 |
/**
* @notice Checks if a Satoshible can still be used for a discounted mint
* @dev Uses bitwise operators to find the bit representing the Satoshible
* @param _satId Original Satoshible token ID
* @return isAvailable True if _satId can be used for a discounted mint
*/ | function satIsAvailableForDiscountMint(
uint256 _satId
)
public
view
returns (bool isAvailable)
{
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
isAvailable = satDiscountBitfields[page] >> shift & 1 == ... | 0.8.9 |
/**
* @notice Verifies a merkle proof for a monster ID and its prime parts
* @param _monsterId Monster token ID
* @param _monsterPrimeParts Bitfield of the monster's prime parts
* @param _proof Merkle proof be verified
* @return isVerified True if the merkle proof is verified
*/ | function verifyMonsterPrimeParts(
uint256 _monsterId,
uint256 _monsterPrimeParts,
bytes32[] calldata _proof
)
public
view
returns (bool isVerified)
{
bytes32 node = keccak256(
abi.encodePacked(
_monsterId,
... | 0.8.9 |
/**
* @notice Verifies a merkle proof for an account's whitelisted tokens
* @param _account Account to verify
* @param _whitelistedTokens Number of whitelisted tokens for _account
* @param _proof Merkle proof to be verified
* @return isVerified True if the merkle proof is verified
*/ | function verifyWhitelisted(
address _account,
uint256 _whitelistedTokens,
bytes32[] calldata _proof
)
public
pure
returns (bool isVerified)
{
bytes32 node = keccak256(
abi.encodePacked(
_account,
_whi... | 0.8.9 |
/**
* @dev Base monster minting function, calculates price with discounts
* @param _numberOfTokens Number of monster tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
*/ | function _doMintTokens(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount
)
private
{
require(
saleIsActive == true,
"Sale must be active"
);
require(
_numberOfTokens >= 1,
"Need at least 1 t... | 0.8.9 |
/**
* @dev Marks a Satoshible ID as having been used for a discounted mint
* @param _satId Satoshible ID that was used for a discounted mint
*/ | function _useSatForDiscountMint(
uint256 _satId
)
private
onlySatHolder(_satId)
{
require(
satIsAvailableForDiscountMint(_satId) == true,
"Sat for discount already used"
);
unchecked {
uint256 page = _satId / 256;
... | 0.8.9 |
/**
* @dev Initializes prime token ID offsets
*/ | function _initializePrimeIdOffsets()
private
{
unchecked {
primeIdOffset[FRANKENSTEIN] = ALPHA;
primeIdOffset[WEREWOLF] = ALPHA + 166;
primeIdOffset[VAMPIRE] = ALPHA + 332;
primeIdOffset[ZOMBIE] = ALPHA + 498;
primeIdOffset[INVALID]... | 0.8.9 |
// bCalled used to prevent reentrancy attack | function approveAndCall(
address _spender,
uint256 _value,
bytes memory _data
)
public
payable
onlyNotBlacklisted
whenNotPaused
returns (bool)
{
require(bCalled == false);
require(_spender != address(this));
req... | 0.5.3 |
/**
* Constructor for Zigilua
*/ | function Zigilua() public
{
balances[msg.sender] = 79700000000;
totalSupply = 79700000000;
name = "ZigiLua";
decimals = 0;
symbol = "ZGL";
zigWallet = msg.sender;
_crrStage = 0;... | 0.4.22 |
/**
* Allows to buy zigs (ZGL) from DApps
*
* @param wai {uint256} Desired amount, in wei
*
* @return {uint256[]} [wai, _usd, amount, owner balance, user balance] Useful for debugging purposes
*/ | function buy(uint256 wai) public payable returns (uint256[5])
{
uint256 amount = ((wai * _usd * 10 * ZIGS_BY_STAGE[_crrStage]) / (1e18));
require(balances[zigWallet] >= amount);
require(amount >= (2000 * (1 / ZIGS_BY_STAGE[_crrStage])));
balances[zigWallet] = (balances[zigW... | 0.4.22 |
//This collateral function is needed to let everyone withraw the eventual staked voting tokens still held in the proposal and give back the to the BuidlersFund wallet | function withdraw(bool terminateFirst) public {
//Terminate or withraw the Proposal
if(terminateFirst) {
IMVDFunctionalityProposal(PROPOSAL).terminate();
} else {
IMVDFunctionalityProposal(PROPOSAL).withdraw();
}
//Give back BUIDL Voting Tokens to the BuildersFund Wallet
IERC20 token = IERC20(... | 0.6.12 |
/**
* Create a new subscription. Must be called by the subscriber's account.
* First payment of `daiCents` is paid on creation.
* Actual payment is made in Wrapped Ether (wETH) using currenct DAI-ETH conversion rate.
* @param receiver address
* @param daiCents subscription amount in hundredths of DAI
* @par... | function subscribe(address receiver, uint daiCents, uint32 interval) external {
uint weiAmount = daiCentsToEthWei(daiCents, ethPriceInDaiWad());
uint64 existingIndex = subscriberReceiver[msg.sender][receiver];
require(subscriptions[existingIndex].daiCents == 0, "Subscription exists");
... | 0.5.2 |
/**
* Deactivate a subscription. Must be called by the subscriber's account.
* Payments cannot be collected from deactivated subscriptons.
* @param receiver address used to identify the unique subscriber-receiver pair.
* @return success
*/ | function deactivateSubscription(address receiver) external returns (bool) {
uint64 index = subscriberReceiver[msg.sender][receiver];
require(index != 0, "Subscription does not exist");
Subscription storage sub = subscriptions[index];
require(sub.isActive, "Subscription is already d... | 0.5.2 |
/**
* Reactivate a subscription. Must be called by the subscriber's account.
* If less than one interval has passed since the last payment, no payment is collected now.
* Otherwise it is treated as a new subscription starting now, and the first payment is collected.
* No back-payments are collected.
* @param ... | function reactivateSubscription(address receiver) external returns (bool) {
uint64 index = subscriberReceiver[msg.sender][receiver];
require(index != 0, "Subscription does not exist");
Subscription storage sub = subscriptions[index];
require(!sub.isActive, "Subscription is already ... | 0.5.2 |
/**
* A read-only version of executeDebits()
* Calculates uncollected *funded* payments for a receiver.
* @param receiver address
* @return total unclaimed value in wei
*/ | function getTotalUnclaimedPayments(address receiver) external view returns (uint) {
uint totalPayment = 0;
uint ethPriceWad = ethPriceInDaiWad();
for (uint i = 0; i < receiverSubs[receiver].length; i++) {
Subscription storage sub = subscriptions[receiverSubs[receiver][i]];
... | 0.5.2 |
/**
* Calculates a subscriber's total outstanding payments in daiCents
* @param subscriber address
* @param time in seconds. If `time` < `now`, then we simply use `now`
* @return total amount owed at `time` in daiCents
*/ | function outstandingBalanceUntil(address subscriber, uint time) external view returns (uint) {
uint until = time <= now ? now : time;
uint64[] memory subs = subscriberSubs[subscriber];
uint totalDaiCents = 0;
for (uint64 i = 0; i < subs.length; i++) {
Subscription me... | 0.5.2 |
/**
* Helper function to search for and delete an array element without leaving a gap.
* Array size is also decremented.
* DO NOT USE if ordering is important.
* @param array array to be modified
* @param element value to be removed
*/ | function deleteElement(uint64[] storage array, uint64 element) internal {
uint lastIndex = array.length.sub(1);
for (uint i = 0; i < array.length; i++) {
if (array[i] == element) {
array[i] = array[lastIndex];
delete(array[lastIndex]);
ar... | 0.5.2 |
/**
* Calculates how many whole unpaid intervals (will) have elapsed since the last payment at a specific `time`.
* DOES NOT check if subscriber account is funded.
* @param sub Subscription object
* @param time timestamp in seconds
* @return number of unpaid intervals
*/ | function calculateUnpaidIntervalsUntil(Subscription memory sub, uint time) internal view returns (uint) {
require(time >= now, "don't use a time before now");
if (time > sub.nextPaymentTime) {
return ((time.sub(sub.nextPaymentTime)).div(sub.interval)).add(1);
}
retur... | 0.5.2 |
/**
* @notice buy weapon and add it to a token's weapon collection
* @dev weaponId n can only be bought if the token owns weaponId - 1 (id 9 and up)
* @param _tokenId - the token's id
* @param _weaponId - the desired weapon's id
*/ | function buyWeapon(uint256 _tokenId, uint256 _weaponId) public {
require(
msg.sender == raiders.ownerOf(_tokenId) ||
hunt.isStaker(msg.sender, _tokenId),
"Not allowed"
);
require(tokenToWeapon[_tokenId][_weaponId] == false, "Already owned");
if (_w... | 0.8.9 |
// 0 -> obtc, 1 -> renBTC, 2 -> wBTC | function trade(int128 token, uint amount, uint min_dy) public whenNotPaused nonReentrant {
if(token == 1) {
renBTC.safeTransferFrom(msg.sender, address(this), amount);
renBTC.approve(address(sso), amount);
} else if(token == 2) {
wBTC.safeTransferFrom(msg.sender, addr... | 0.6.12 |
// Transfer funds. | function transfer(address _to, uint256 _amount) public returns (bool) {
require(_to != address(0));
require(_amount <= accounts[msg.sender].balance);
// Enable the receiver if the sender is the exchange.
if (msg.sender == owner && !accounts[_to].enabled) {
accounts[_to].... | 0.4.18 |
/// @dev make any kind of request that may be answered with a file.This function is only called by Mage | function submitNewRequest(
string memory _orderTitle,
string memory _description,
string memory _zPaper,
uint _tokenPerContributor,
uint _tokenPerLaboratory,
uint _totalContributors,
string memory _zarelaCategory,
uint _businessCategory,
string mem... | 0.7.6 |
/// @dev Confirm the signals sent by angels only by Requester (Mage) of that signal.
/// The selection of files is based on their index. | function confirmContributor(
uint _orderId,
uint[]memory _index
)
public
onlyRequester(_orderId)
checkOrderId(_orderId)
{
Order storage myorder = orders[_orderId];
require(_index.length >= 1,"You Should Select One At Least");
require(_index.length... | 0.7.6 |
/// @dev retrieves the value of each the specefic order by `_orderId`
/// @return the contributors addresses , the Laboratory addresses , Time to send that signal by the angel , Laboratory or angel gained reward? , Status (true , false) of confirmation , Zarela day sent that signal | function getOrderData(
uint _orderId
)
public
checkOrderId (_orderId)
view returns (
address[] memory,
address[] memory,
uint[]memory,
bool[]memory,
bool[] memory,
uint[] memory)
{
return (
... | 0.7.6 |
// swaps any combination of ERC-20/721/1155
// User needs to approve assets before invoking swap
// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!! | function multiAssetSwap(
ERC20Details memory erc20Details,
SpecialTransferHelper.ERC721Details[] memory erc721Details,
ERC1155Details[] memory erc1155Details,
ConverstionDetails[] memory converstionDetails,
MarketRegistry.TradeDetails[] memory tradeDetails,
address[] memo... | 0.8.11 |
// Utility function that is used for free swaps for sponsored markets
// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!! | function multiAssetSwapWithoutFee(
ERC20Details memory erc20Details,
SpecialTransferHelper.ERC721Details[] memory erc721Details,
ERC1155Details[] memory erc1155Details,
ConverstionDetails[] memory converstionDetails,
MarketRegistry.TradeDetails[] memory tradeDetails,
addr... | 0.8.11 |
// Generic function to determine winner. Aim to be called any number of times | function drawTicket (uint randomiserNumber, bytes32 randomHash) internal view returns(uint pickedTicket, bytes32 newGeneratedRandomHash) {
bytes32 newRandomHash;
uint pickTicket;
for (int i = 0; i < 10; i++) {
newRandomHash = keccak256(abi.encodePacked(randomHash, block... | 0.8.9 |
// ------------------------------------------------------------------------
// CrowdSale Function 1,800,000 RCALLS Tokens per 1 ETH
// ------------------------------------------------------------------------ | function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 2400000;
} else {
tokens = msg.value * 1800000;
}
balances[owner] = safeSub(balances[owner], tokens);
... | 0.4.24 |
/*
* Allows the owner to change the return rate for a given bracket
* NOTE: changes to this rate will only affect those that stake AFTER this change.
* Will not affect the currently staked amounts.
*/ | function changeReturnRateForBracket(uint256 _percentage, uint256 _stakeBracket) public onlyOwner {
require(_stakeBracket <= 4);
// TAKE NOTE OF FORMATTING:
// stakeReward[0] = 25;
// stakeReward[1] = 55;
// stakeReward[2] = 190;
// stakeReward[3] = 450;
// stakeRe... | 0.7.0 |
/***********************************|
| Only Controller |
|__________________________________*/ | function energize(
address contractAddress,
uint256 tokenId,
address assetToken,
uint256 assetAmount
)
external
override
onlyController
returns (uint256 yieldTokensAmount)
{
uint256 uuid = contractAddress.getTokenUUID(tokenId);
address wallet = _wallets[uuid];
// Deposit... | 0.6.12 |
/**
* @dev Create an order for your NFT and other people can pairing their NFT to exchange
* @notice You must call receiveErc721Token method first to send your NFT to exchange contract,
* if your NFT have matchorder pair with other order, then they will become Invalid until you
* delete this order.
* @param c... | function createOrder(
address contractAddress,
uint256 tokenId
)
external
onlySenderIsOriginalOwner(
contractAddress,
tokenId
)
{
bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender));
require(OrderToOwne... | 0.5.6 |
/**
* @dev Remove order information on exchange contract
* @param sender order's owner
* @param orderHash order's hash
*/ | function _removeOrder(
address sender,
bytes32 orderHash
)
internal
{
OrderToExist[orderHash] = false;
delete OrderToOwner[orderHash];
uint256 orderIndex = OrderToIndex[orderHash];
uint256 lastOrderIndex = OwnerToOrders[sender].length.sub(1);
... | 0.5.6 |
/**
* @dev If your are interested in specfic order's NFT, create a matchorder and pair with it so order's owner
* can know and choose to exchange with you
* @notice You must call receiveErc721Token method first to send your NFT to exchange contract,
* if your NFT already create order, then you will be prohibit ... | function createMatchOrder(
address contractAddress,
uint256 tokenId,
bytes32 orderHash
)
external
onlySenderIsOriginalOwner(
contractAddress,
tokenId
)
{
bytes32 matchOrderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.... | 0.5.6 |
/**
* @dev delete matchorder information on exchange contract
* @param matchOrderHash matchorder's hash
* @param orderHash order's hash which matchorder pair with
*/ | function deleteMatchOrder(
bytes32 matchOrderHash,
bytes32 orderHash
)
external
{
require(MatchOrderToOwner[matchOrderHash] == msg.sender, "match order doens't belong to this address" );
require(OrderToExist[orderHash] == true, "this order is not exist");
_rem... | 0.5.6 |
/**
* @dev order's owner can choose NFT to exchange from it's match order array, when function
* execute, order will be deleted, both NFT will be exchanged and send to corresponding address.
* @param order order's hash which matchorder pair with
* @param matchOrder matchorder's hash
*/ | function exchangeToken(
bytes32 order,
bytes32 matchOrder
)
external
{
require(OrderToOwner[order] == msg.sender, "this order doesn't belongs to this address");
OrderObj memory orderObj = HashToOrderObj[order];
uint index = OrderToMatchOrderIndex[order][matc... | 0.5.6 |
/**
* @dev if you want to create order and matchorder on exchange contract, you must call this function
* to send your NFT to exchange contract, if your NFT is followed erc165 and erc721 standard, exchange
* contract will checked and execute sucessfully, then contract will record your information so you
* don'... | function receiveErc721Token(
address contractAddress,
uint256 tokenId
)
external
{
bool checkSupportErc165Interface = false;
if(contractAddress != CryptoKittiesAddress){
for(uint i = 0; i < SupportNFTInterface.length; i++){
if(contract... | 0.5.6 |
/**
* @dev add token and OrderObj information on exchange contract, because order hash and matchorder
* hash are same, so one NFT have mapping to one OrderObj
* @param sender NFT's owner
* @param contractAddress NFT's contract address
* @param tokenId NFT's id
*/ | function _addToken(
address sender,
address contractAddress,
uint256 tokenId
)
internal
{
bytes32 matchOrderHash = keccak256(abi.encodePacked(contractAddress, tokenId, sender));
MatchOrderToOwner[matchOrderHash] = sender;
HashToOrderObj[matchOr... | 0.5.6 |
/**
* @dev send your NFT back to address which you send token in, if your NFT still have open order,
* then order will be deleted
* @notice matchorder will not be deleted because cost too high, but they will be useless and other
* people can't choose your match order to exchange
* @param contractAddress NFT's... | function sendBackToken(
address contractAddress,
uint256 tokenId
)
external
onlySenderIsOriginalOwner(
contractAddress,
tokenId
)
{
bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, msg.sender));
if(OrderToExist[o... | 0.5.6 |
/**
* @dev Drive NFT contract to send NFT to corresponding address
* @notice because cryptokittes contract method are not the same as general NFT contract, so
* need treat it individually
* @param sendAddress NFT's owner
* @param contractAddress NFT's contract address
* @param tokenId NFT's id
*/ | function _sendToken(
address sendAddress,
address contractAddress,
uint256 tokenId
)
internal
{
if(contractAddress != CryptoKittiesAddress){
Erc721Interface erc721Contract = Erc721Interface(contractAddress);
require(erc721Contract.ownerOf(... | 0.5.6 |
/**
* @dev remove token and OrderObj information on exchange contract
* @param contractAddress NFT's contract address
* @param tokenId NFT's id
*/ | function _removeToken(
address contractAddress,
uint256 tokenId
)
internal
{
address owner = TokenToOwner[contractAddress][tokenId];
bytes32 orderHash = keccak256(abi.encodePacked(contractAddress, tokenId, owner));
delete HashToOrderObj[orderHash];
... | 0.5.6 |
// See which address owns which tokens | function tokensOfOwner(address addr)
public
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(addr);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(addr... | 0.8.7 |
// Exclusive presale minting | function mintPresale(uint256 amount) internal {
require(amount > 0, "amount should not be zero..");
// uint256 reservedAmt = presaleReserved[msg.sender];
require(
amount <= presaleReserved[msg.sender],
"mintPresale Erorr: minted reserved tokens or not allowed"
... | 0.8.7 |
// Standard mint function1 | function mintToken(uint256 amount) internal {
require(amount <= 10, "Only 10 tokens are allowed to mint once");
require(msg.value == price * amount, "Wrong amount of ETH sent");
require(saleActive, "Sale isn't active");
require(
_tokenIdCounter.current() + amount <= MAX_... | 0.8.7 |
//withdraw ethers() from contract onlyy Admin | function withdrawfunds() public payable onlyOwner {
require(
msg.sender == owner(),
"withdrawfunds: only Owner can call this function"
);
require(
address(this).balance != 0,
"withdrawfunds :no balance is in contract"
);
pa... | 0.8.7 |
// Admin minting function to reserve tokens for the team, collabs, customs and giveaways | function mintReserved(uint256 _amount) public onlyOwner {
// Limited to a publicly set amount
require(_amount > 0, "Invalid amount is given");
require(_amount <= reserved, "Can't reserve more than set amount");
reserved -= _amount;
for (uint256 i = 1; i <= _amount; i++) {
... | 0.8.7 |
// callable by owner only, after specified time, only for Tokens implementing ERC20 | function withdrawERC20Amount(address _tokenContract, uint256 _amount) onlyOwner public {
ERC20 token = ERC20(_tokenContract);
uint256 tokenBalance = token.balanceOf(this);
require(tokenBalance >= _amount, "Not enough funds in the reserve");
token.transfer(owner, _amount);
emit Wi... | 0.4.24 |
/// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `_implementer` or not.
/// @param _interfaceHash keccak256 hash of the name of the interface
/// @param _implementer Address for which the contract will implement the interface
/// @return ERC1820_ACCEPT_MAGIC only if th... | function canImplementInterfaceForAddress(bytes32 _interfaceHash, address _implementer) external view returns(bytes32) {
// keccak256(abi.encodePacked("ERC777TokensRecipient")) == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b
if (_implementer == address(this) && _interfaceHash == 0xb281fc8c12954... | 0.6.2 |
// this function is effectively map.entries.slice(1:), but that doesn't work with storage arrays in this version of solc so we have to do it by hand | function enumerate(Map storage map) internal view returns (Entry[] memory) {
// output array is one shorter because we use a 1-indexed array
Entry[] memory output = new Entry[](map.entries.length - 1);
// first element in the array is just a placeholder (0,0), so we copy from element 1 to end
for (uint256 i = ... | 0.6.2 |
/// @notice starts the recovery process. must be called by a previously registered recovery address. recovery will complete in a number of days dependent on the address that initiated the recovery | function startRecovery() external {
require(recoveryDelaysInDays.contains(msg.sender), "Caller is not registered as a recoverer for this wallet.");
uint16 _proposedRecoveryDelayInDays = recoveryDelaysInDays.get(msg.sender);
bool _inRecovery = activeRecoveryAddress != address(0);
if (_inRecovery) {
// NOTE: ... | 0.6.2 |
/// @notice finishes the recovery process after the necessary delay has elapsed. callable by anyone in case the keys controlling the active recovery address have been lost, since once this is called a new recovery (with a potentially lower recovery priority) can begin. | function finishRecovery() external onlyDuringRecovery {
require(block.timestamp >= activeRecoveryEndTime, "You must wait until the recovery delay is over before finishing the recovery.");
address _oldOwner = owner;
owner = activeRecoveryAddress;
resetRecovery();
emit RecoveryFinished(_oldOwner, owner);
} | 0.6.2 |
/// @notice deploy a contract from this contract.
/// @dev uses create2, so the address of the deployed contract will be deterministic
/// @param _value the amount of ETH that should be supplied to the contract creation call
/// @param _data the deployment bytecode to execute
/// @param _salt the salt used for determin... | function deploy(uint256 _value, bytes calldata _data, uint256 _salt) external payable onlyOwner onlyOutsideRecovery returns (address) {
require(address(this).balance >= _value, "Wallet does not have enough funds available to deploy the contract.");
require(_data.length != 0, "Contract deployment must contain byteco... | 0.6.2 |
/// @notice executes an arbitrary contract call by this wallet. allows the wallet to send ETH, transfer tokens, use dapps, etc.
/// @param _to contract address to call or send to
/// @param _value the amount of ETH to attach to the call
/// @param _data the calldata to supply to `_to`
/// @dev `_data` is of the same f... | function execute(address payable _to, uint256 _value, bytes calldata _data) external payable onlyOwner onlyOutsideRecovery returns (bytes memory) {
require(_to != address(0), "Transaction execution must contain a destination. If you meant to deploy a contract, use deploy instead.");
require(address(this).balance >... | 0.6.2 |
/// @notice determines the amount of needed collateral for a given position (qty and price)
/// @param priceFloor lowest price the contract is allowed to trade before expiration
/// @param priceCap highest price the contract is allowed to trade before expiration
/// @param qtyMultiplier multiplier for qty from base uni... | function calculateCollateralToReturn(
uint priceFloor,
uint priceCap,
uint qtyMultiplier,
uint longQty,
uint shortQty,
uint price
) pure internal returns (uint)
{
uint neededCollateral = 0;
uint maxLoss;
if (longQty > 0) { // c... | 0.5.2 |
// expiration date or outside of our tradeable ranges. | function checkSettlement() internal {
require(!isSettled, "Contract is already settled"); // already settled.
uint newSettlementPrice;
if (now > EXPIRATION) { // note: miners can cheat this by small increments of time (minutes, not hours)
isSettled = true; //... | 0.5.2 |
/// @notice Called by a user that currently holds both short and long position tokens and would like to redeem them
/// for their collateral.
/// @param marketContractAddress address of the market contract to redeem tokens for
/// @param qtyToRedeem quantity of long / short tokens to red... | function redeemPositionTokens(
address marketContractAddress,
uint qtyToRedeem
) external onlyWhiteListedAddress(marketContractAddress)
{
MarketContract marketContract = MarketContract(marketContractAddress);
marketContract.redeemLongToken(qtyToRedeem, msg.sender);
... | 0.5.2 |
/// @param marketContractAddress address of the MARKET Contract being traded.
/// @param longQtyToRedeem qty to redeem of long tokens
/// @param shortQtyToRedeem qty to redeem of short tokens | function settleAndClose(
address marketContractAddress,
uint longQtyToRedeem,
uint shortQtyToRedeem
) external onlyWhiteListedAddress(marketContractAddress)
{
MarketContract marketContract = MarketContract(marketContractAddress);
require(marketContract.isPostSettle... | 0.5.2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.