comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
// TNTOO withdraw as ETH | function withdraw(address _target, uint _amount, uint _fee) public {
require(_amount <= quotaOf[_target]);
uint finalAmount = _amount - _fee;
uint ethAmount = finalAmount / ratio;
require(ethAmount <= allEther);
// fee
if (msg.sender == owner && _target != ... | 0.4.20 |
/**
* @author allemanfredi
* @notice given an input amount, returns the output
* amount with slippage and with fees. This fx is
* to check approximately onchain the slippage
* during a swap
*/ | function calculateSlippageAmountWithFees(
uint256 _amountIn,
uint256 _allowedSlippage,
uint256 _rateIn,
uint256 _rateOut
) internal pure returns (uint256) {
require(_amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
uint256 slippageAmount = _amountIn
... | 0.5.16 |
/**
* @author allemanfredi
* @notice given 2 inputs amount, it returns the
* rate percentage between the 2 amounts
*/ | function calculateRate(uint256 _amountIn, uint256 _amountOut) internal pure returns (uint256) {
require(_amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
require(_amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT");
return
_amountIn > _amountOut
... | 0.5.16 |
/**
* @author allemanfredi
* @notice returns the slippage for a trade without counting the fees
*/ | function calculateSlippage(
uint256 _amountIn,
uint256 _reserveIn,
uint256 _reserveOut
) internal pure returns (uint256) {
require(_amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT");
uint256 price = _reserveOut.mul(10**18).div(_reserveIn);
uint256 quote = _... | 0.5.16 |
/**
* @dev Burns tokens/shares and retuns the ETH value, after fee, of those.
*/ | function withdrawETH(uint256 shares) external whenNotShutdown nonReentrant {
require(shares != 0, "Withdraw must be greater than 0");
uint256 sharesAfterFee = _handleFee(shares);
uint256 amount = sharesAfterFee.mul(totalValue()).div(totalSupply());
_burn(_msgSender(), sharesAfterFee)... | 0.6.12 |
// // Minted the reserve | function reserveMint(address _to, uint256 _amount) external onlyOwner() {
require( _amount <= reserved, "Exceeds reserved supply" );
uint256 supply = totalSupply();
for(uint256 i; i < _amount; i++){
_safeMint( _to, supply + i );
}
reserved -= _amount;
} | 0.8.7 |
// Helps check which Metavader this wallet owner owns | function collectionInWallet(address _owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
ret... | 0.8.7 |
/**
* @notice Burn all user's UniV2 staked in the ModifiedUnipool,
* unwrap the corresponding amount of WETH into ETH, collect
* rewards matured from the UniV2 staking and sent it to msg.sender.
* User must approve this contract to withdraw the corresponding
* amount of his UniV2 ba... | function unstake() public returns (bool) {
uint256 uniV2SenderBalance = modifiedUnipool.balanceOf(msg.sender);
require(
modifiedUnipool.allowance(msg.sender, address(this)) >= uniV2SenderBalance,
"RewardedPltcWethUniV2Pair: amount not approved"
);
modifiedUnipool... | 0.5.16 |
/**
* @notice Wrap the Ethereum sent into WETH, swap the amount sent / 2
* into WETH and put them into a PLTC/WETH Uniswap pool.
* The amount of UniV2 token will be sent to ModifiedUnipool
* in order to mature rewards.
* @param _user address of the user who will have UniV2 tokens in Modifie... | function _stakeFor(address _user, uint256 _amount) internal {
uint256 wethAmountIn = _amount / 2;
(uint256 pltcReserve, uint256 wethReserve, ) = uniV2.getReserves();
uint256 pltcAmountOut = UniswapV2Library.getAmountOut(wethAmountIn, wethReserve, pltcReserve);
require(
allow... | 0.5.16 |
// function Kill() public {
// if(msg.sender == owner) {
// selfdestruct(owner);
// }
// } | function bytesToString (bytes32 data) returns (string) {
bytes memory bytesString = new bytes(32);
for (uint j=0; j<32; j++) {
byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
if (char != 0) {
bytesString[j] = char;
}
}
ret... | 0.4.11 |
//1 ether = 1 spot | function joinPot() public payable {
assert(now < endTime);
//for each ether sent, reserve a spot
for(uint i = msg.value; i >= minBetSize; i-= minBetSize) {
potMembers.push(msg.sender);
totalBet+= minBetSize;
potSize += 1;
}
potSizeChanged(potS... | 0.4.11 |
// Signature methods | function splitSignature(bytes sig)
internal
pure
returns (uint8, bytes32, bytes32)
{
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(s... | 0.4.24 |
//Private sale minting (reserved for Loot owners) | function mintWithLoot(uint lootId) public payable nonReentrant {
require(lootersPrice <= msg.value, "Ether value sent is not correct");
require(lootContract.ownerOf(lootId) == msg.sender, "Not the owner of this loot");
require(!_exists(lootId), "This token has already been minted");
... | 0.8.7 |
//Public sale minting | function mint(uint lootId) public payable nonReentrant {
require(publicPrice <= msg.value, "Ether value sent is not correct");
require(lootId > 8000 && lootId <= 12000, "Token ID invalid");
require(!_exists(lootId), "This token has already been minted");
_safeMint(msg.sender, lootI... | 0.8.7 |
/**
* Should allow any address to trigger it, but since the calls are atomic it should do only once per day
*/ | function triggerTokenSend() external whenNotPaused {
/* Require TGE Date already been set */
require(TGEDate != 0, "TGE date not set yet");
/* TGE has not started */
require(block.timestamp > TGEDate, "TGE still hasn´t started");
/* Test that the call be only done once per ... | 0.5.8 |
/**
* @dev Allows to lock an amount of tokens of specific addresses.
* Available only to the owner.
* Can be called once.
* @param addresses array of addresses.
* @param values array of amounts of tokens.
* @param times array of Unix times.
*/ | function lock(address[] calldata addresses, uint256[] calldata values, uint256[] calldata times) external onlyOwner {
require(!_started);
require(addresses.length == values.length && values.length == times.length);
for (uint256 i = 0; i < addresses.length; i++) {
require(balanc... | 0.5.7 |
/**
* @dev modified internal transfer function that prevents any transfer of locked tokens.
* @param from address The address which you want to send tokens from
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/ | function _transfer(address from, address to, uint256 value) internal {
if (_locked[from].locked) {
for (uint256 i = 0; i < _locked[from].batches.length; i++) {
if (block.timestamp <= _locked[from].batches[i].time) {
require(value <= balanceOf(from).sub(_locked... | 0.5.7 |
/**
* transfer() - transfer tokens from msg.sender balance
* to requested account
*
* @param to - target address to transfer tokens
* @param value - ammount of tokens to transfer
*
* @return - success / failure of the transaction
*/ | function transfer(address to, uint256 value) returns (bool success) {
if (balances[msg.sender] >= value && value > 0) {
// do actual tokens transfer
balances[msg.sender] -= value;
balances[to] += value;
// ri... | 0.4.2 |
/**
* transferFrom() -
*
* @param from -
* @param to -
* @param value -
*
* @return
*/ | function transferFrom(address from, address to, uint256 value) returns (bool success) {
if ( balances[from] >= value &&
allowed[from][msg.sender] >= value &&
value > 0) {
// do the actual transfer
ba... | 0.4.2 |
/**
*
* approve() - function approves to a person to spend some tokens from
* owner balance.
*
* @param spender - person whom this right been granted.
* @param value - value to spend.
*
* @return true in case of succes, otherwise failure
*
*/ | function approve(address spender, uint256 value) returns (bool success) {
// now spender can use balance in
// ammount of value from owner balance
allowed[msg.sender][spender] = value;
// rise event about the transaction
Approval(msg.sender, spender, val... | 0.4.2 |
/**
* Constructor of the contract.
*
* Passes address of the account holding the value.
* HackerGold contract itself does not hold any value
*
* @param multisig address of MultiSig wallet which will hold the value
*/ | function HackerGold(address multisig) {
wallet = multisig;
// set time periods for sale
milestones = milestones_struct(
1476799200, // P1: GMT: 18-Oct-2016 14:00 => The Sale Starts
1478181600, // P2: GMT: 03-Nov-2016 14:00 => 1st Price Ladder
... | 0.4.2 |
/**
* Creates HKG tokens.
*
* Runs sanity checks including safety cap
* Then calculates current price by getPrice() function, creates HKG tokens
* Finally sends a value of transaction to the wallet
*
* Note: due to lack of floating point types in Solidity,
* contract assumes that last 3 digits in toke... | function createHKG(address holder) payable {
if (now < milestones.p1) throw;
if (now >= milestones.p6) throw;
if (msg.value == 0) throw;
// safety cap
if (getTotalValue() + msg.value > SAFETY_LIMIT) throw;
uint tokens = msg.value * getPrice() ... | 0.4.2 |
/**
* Denotes complete price structure during the sale.
*
* @return HKG amount per 1 ETH for the current moment in time
*/ | function getPrice() constant returns (uint result) {
if (now < milestones.p1) return 0;
if (now >= milestones.p1 && now < milestones.p2) {
return BASE_PRICE;
}
if (now >= milestones.p2 && now < milestones.p3) {
... | 0.4.2 |
// ONLY-STAKING-CONTRACT FUNCTIONS | function validateJoinPackage(address _from, address _to, uint8 _type, uint _dabAmount, uint _gemAmount)
onlyContractAContract
public
view
returns (bool)
{
Package storage package = packages[_to];
Balance storage balance = balances[_from];
return _type > uint8(PackageType.M0) &&
_typ... | 0.4.25 |
// PRIVATE-FUNCTIONS | function updatePackageInfo(address _to, PackageType _packageType, uint _dabAmount, uint _gemAmount) private {
Package storage package = packages[_to];
package.packageType = _packageType;
package.lastPackage = _dabAmount.add(_gemAmount);
package.dabAmount = package.dabAmount.add(_dabAmount);
pac... | 0.4.25 |
/**
* @dev Remove party.
* @param _participantIndex Index of the participant in the participants array.
*/ | function removeParty(uint256 _participantIndex) onlyOwner canRemoveParty external {
require(_participantIndex < participants.length, "Participant does not exist");
address participant = participants[_participantIndex];
address token = tokenByParticipant[participant];
delete isPar... | 0.4.24 |
/**
* @dev Withdraw tokens
*/ | function withdraw() onlyParticipant canWithdraw external {
for (uint i = 0; i < participants.length; i++) {
address token = tokenByParticipant[participants[i]];
SwapOffer storage offer = offerByToken[token];
if (offer.participant == msg.sender) {
contin... | 0.4.24 |
/**
* @dev Withdraw swap fee
*/ | function withdrawFee() onlyOwner canWithdrawFee external {
for (uint i = 0; i < participants.length; i++) {
address token = tokenByParticipant[participants[i]];
SwapOffer storage offer = offerByToken[token];
uint256 tokensAmount = _withdrawableFee(offer);
... | 0.4.24 |
/**
* @dev Reclaim tokens if a participant has deposited too much or if the swap has been canceled.
*/ | function reclaim() onlyParticipant canReclaim external {
address token = tokenByParticipant[msg.sender];
SwapOffer storage offer = offerByToken[token];
uint256 currentBalance = offer.token.balanceOf(address(this));
uint256 availableForReclaim = currentBalance
.sub(offe... | 0.4.24 |
/**
* @notice Create keeper and maintainer list
* @dev Create lists and add governor into the list.
* NOTE: Any function with onlyKeeper and onlyMaintainer modifier will not work until this function is called.
* NOTE: Due to gas constraint this function cannot be called in constructor.
*/ | function init() external onlyGovernor {
require(address(keepers) == address(0), "list-already-created");
IAddressListFactory _factory = IAddressListFactory(0xded8217De022706A191eE7Ee0Dc9df1185Fb5dA3);
keepers = IAddressList(_factory.createList());
maintainers = IAddressList(_factory.crea... | 0.8.3 |
/// @dev Add strategy | function addStrategy(
address _strategy,
uint256 _interestFee,
uint256 _debtRatio,
uint256 _debtRate
) public onlyGovernor {
require(_strategy != address(0), "strategy-address-is-zero");
require(!strategy[_strategy].active, "strategy-already-added");
totalDebt... | 0.8.3 |
/**
* @dev Revoke and remove strategy from array. Update withdraw queue.
* Withdraw queue order should not change after remove.
* Strategy can be removed only after it has paid all debt.
* Use migrate strategy if debt is not paid and want to upgrade strat.
*/ | function removeStrategy(uint256 _index) external onlyGovernor {
address _strategy = strategies[_index];
require(strategy[_strategy].active, "strategy-not-active");
require(strategy[_strategy].totalDebt == 0, "strategy-has-debt");
delete strategy[_strategy];
strategies[_index] = s... | 0.8.3 |
/// @dev update withdrawal queue | function updateWithdrawQueue(address[] memory _withdrawQueue) external onlyMaintainer {
uint256 _length = _withdrawQueue.length;
require(_length > 0, "withdrawal-queue-blank");
require(_length == withdrawQueue.length && _length == strategies.length, "incorrect-withdraw-queue-length");
fo... | 0.8.3 |
/**
@dev Strategy call this in regular interval.
@param _profit yield generated by strategy. Strategy get performance fee on this amount
@param _loss Reduce debt ,also reduce debtRatio, increase loss in record.
@param _payback strategy willing to payback outstanding above debtLimit. no performance fee on this amou... | function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external onlyStrategy {
require(token.balanceOf(_msgSender()) >= (_profit + _payback), "insufficient-balance-in-strategy");
if (_loss != 0) {
_reportLoss(_msgSender(), _loss);
}
... | 0.8.3 |
/**
* @dev Before burning hook.
* withdraw amount from strategies
*/ | function _beforeBurning(uint256 _share) internal override returns (uint256 actualWithdrawn) {
uint256 _amount = (_share * pricePerShare()) / 1e18;
uint256 _balanceNow = tokensHere();
if (_amount > _balanceNow) {
_withdrawCollateral(_amount - _balanceNow);
_balanceNow = to... | 0.8.3 |
/**
@dev when a strategy report loss, its debtRatio decrease to get fund back quickly.
*/ | function _reportLoss(address _strategy, uint256 _loss) internal {
uint256 _currentDebt = strategy[_strategy].totalDebt;
require(_currentDebt >= _loss, "loss-too-high");
strategy[_strategy].totalLoss += _loss;
strategy[_strategy].totalDebt -= _loss;
totalDebt -= _loss;
uin... | 0.8.3 |
/**
* @dev Check whether every participant has deposited enough tokens for the swap to be confirmed.
*/ | function _haveEveryoneDeposited() internal view returns(bool) {
for (uint i = 0; i < participants.length; i++) {
address token = tokenByParticipant[participants[i]];
SwapOffer memory offer = offerByToken[token];
if (offer.token.balanceOf(address(this)) < offer.tokensTot... | 0.4.24 |
/**
* @dev Get percent of unlocked tokens
*/ | function _getUnlockedTokensPercentage() internal view returns(uint256) {
for (uint256 i = lockupStages.length; i > 0; i--) {
LockupStage storage stage = lockupStages[i - 1];
uint256 stageBecomesActiveAt = startLockupAt.add(stage.secondsSinceLockupStart);
if (now < stage... | 0.4.24 |
/// @dev Allows to send a bid to the auction. | function bid()
external
payable
isValidPayload
timedTransitions
atStage(Stages.AuctionStarted)
returns (uint amount)
{
require(msg.value > 0);
amount = msg.value;
address payable receiver = _msgSender();
// Prevent that m... | 0.6.12 |
/**
* @notice Modify uint256 parameters
* @param parameter Name of the parameter to modify
* @param data New parameter value
**/ | function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "validityFlag") {
require(either(data == 1, data == 0), "ConverterFeed/invalid-data");
validityFlag = data;
} else if (parameter == "scalingFactor") {
require(data > 0, ... | 0.6.7 |
/// @notice Method for deploy new PiNFTTradable contract
/// @param _name Name of NFT contract
/// @param _symbol Symbol of NFT contract | function createNFTContract(string memory _name, string memory _symbol)
external
payable
returns (address)
{
require(msg.value >= platformFee, "Insufficient funds.");
(bool success,) = feeRecipient.call{value: msg.value}("");
require(success, "Transfer failed");... | 0.6.12 |
/**
* @notice Fetch the latest medianPrice and whether it is null or not
**/ | function getResultWithValidity() public view returns (uint256 value, bool valid) {
(uint256 targetValue, bool targetValid) = targetFeed.getResultWithValidity();
(uint256 denominationValue, bool denominationValid) = denominationFeed.getResultWithValidity();
value = multiply(targetValue, denomi... | 0.6.7 |
// ------------------------------------------------------------------------
// internal function applies Deductions upon transfer function
// ------------------------------------------------------------------------ | function _transferAndBurn(address from, address to, uint tokens) internal {
// calculate 1% of the tokens
uint256 onePercentofTokens = _onePercent(tokens);
// burn 1% of tokens
_burn(from, onePercentofTokens);
// transfer 1% to donation wallet
_t... | 0.5.11 |
/// @notice Set or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NF... | function approve(address _approved, uint256 _tokenId) external{
address owner = ownerOf(_tokenId);
uint innerId = tokenId_to_innerId(_tokenId);
require( owner == msg.sender //Require Sender Owns Token
|| AUTHORISED[owner][msg.sender] // or is app... | 0.6.2 |
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// n... | function transferFrom(address _from, address _to, uint256 _tokenId) public {
uint innerId = tokenId_to_innerId(_tokenId);
//Check Transferable
//There is a token validity check in ownerOf
address owner = ownerOf(_tokenId);
require ( owner == msg.sender //Re... | 0.6.2 |
/**
* @notice Returns the current per-block supply interest rate for this aToken
* @return The supply interest rate per block, scaled by 1e18
*/ | function supplyRatePerBlock() external view returns (uint) {
/* We calculate the supply rate:
* underlying = totalSupply × exchangeRate
* borrowsPer = totalBorrows ÷ underlying
* supplyRate = borrowRate × (1-reserveFactor) × borrowsPer
*/
uint exchangeRateMan... | 0.5.16 |
/**
* @notice Sender redeems aTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
... | function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fai... | 0.5.16 |
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Erro... | 0.5.16 |
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this aToken to be liquidated
* @param aTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the und... | function liquidateBorrowInternal(address borrower, uint repayAmount, AToken aTokenCollateral) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attemp... | 0.5.16 |
// public mint | function mint(uint256 _mintAmount) public payable {
require(!paused, "the mint is paused");
uint256 supply = totalSupply();
//require(_mintAmount > 0, "need to mint at least 1 NFT");
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
if (msg.sender != owner()) {
re... | 0.8.7 |
/**
* @dev emergency buy uses last stored affiliate ID
*/ | function()
isActivated()
isHuman()
isWithinLimits(msg.value)
isGameStart()
payable
external
{
// determine if sniper is new or not
determineSID();
// fetch sniper id
uint256 _sID = sIDxAddr_[msg.sender];
... | 0.4.25 |
/**
* @dev withdraws all of your earnings.
* -functionhash-
*/ | function withdraw()
public
isActivated()
isHuman()
{
// grab time
uint256 _now = now;
// fetch player ID
uint256 _sID = sIDxAddr_[msg.sender];
// get their earnings
uint256 _eth = withdrawEarnings(_sID);
... | 0.4.25 |
/**
* @dev logic runs whenever a buy order is executed.
*/ | function buyCore(uint256 _sID, uint256 _affID)
private
{
uint256 _rID = rID_;
//If the sniper does not enter the game through the affiliate, then 10% is paid to the team,
//otherwise, paid to the affiliate.
if(_affID == 0 && spr_[_sID].laff == 0) {
em... | 0.4.25 |
/**
* @dev this is the core logic for any buy that happens.
*/ | function core(uint256 _rID, uint256 _sID, uint256 _eth, uint256 _affID)
private
{
uint256 _now = block.timestamp;
uint256 _value = _eth;
uint256 _laffRearwd = _value / 10;
//affiliate sniper
spr_[_affID].aff = spr_[_affID].aff.add(_laffRearwd);
... | 0.4.25 |
/**
* @dev gets existing or registers new sID. use this when a sniper may be new
* @return sID
*/ | function determineSID()
private
{
uint256 _sID = sIDxAddr_[msg.sender];
// if sniper is new to this version of H1M
if (_sID == 0)
{
// grab their sniper ID, name and last aff ID, from sniper names contract
_sID = SniperBook.getSniperID(msg.sen... | 0.4.25 |
/// @dev Sum vector
/// @param self Storage array containing uint256 type variables
/// @return sum The sum of all elements, does not check for overflow | function sumElements(uint256[] storage self) public view returns(uint256 sum) {
assembly {
mstore(0x60,self_slot)
for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } {
sum := add(sload(add(sha3(0x60,0x20),i)),sum)
}
}
} | 0.4.25 |
/// @dev Returns the max value in an array.
/// @param self Storage array containing uint256 type variables
/// @return maxValue The highest value in the array | function getMax(uint256[] storage self) public view returns(uint256 maxValue) {
assembly {
mstore(0x60,self_slot)
maxValue := sload(sha3(0x60,0x20))
for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } {
switch gt(sload(add(sha3(0x60,0x20),i)), maxValue)
case 1 {
... | 0.4.25 |
/// @dev Returns the minimum value in an array.
/// @param self Storage array containing uint256 type variables
/// @return minValue The highest value in the array | function getMin(uint256[] storage self) public view returns(uint256 minValue) {
assembly {
mstore(0x60,self_slot)
minValue := sload(sha3(0x60,0x20))
for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } {
switch gt(sload(add(sha3(0x60,0x20),i)), minValue)
case 0 {
... | 0.4.25 |
/// @dev Finds the index of a given value in an array
/// @param self Storage array containing uint256 type variables
/// @param value The value to search for
/// @param isSorted True if the array is sorted, false otherwise
/// @return found True if the value was found, false otherwise
/// @return index The index of th... | function indexOf(uint256[] storage self, uint256 value, bool isSorted)
public
view
returns(bool found, uint256 index) {
assembly{
mstore(0x60,self_slot)
switch isSorted
case 1 {
let high := sub(sload(self_slot),1)
let mid := 0
let ... | 0.4.25 |
/// @dev Removes duplicates from a given array.
/// @param self Storage array containing uint256 type variables | function uniq(uint256[] storage self) public returns (uint256 length) {
bool contains;
uint256 index;
for (uint256 i = 0; i < self.length; i++) {
(contains, index) = indexOf(self, self[i], false);
if (i > index) {
for (uint256 j = i; j < self.length - 1; j++){
self[j... | 0.4.25 |
/// @notice Creates an edition by deploying a new proxy. | function createEdition(
AllocatedEditionsStorage.NFTMetadata memory metadata,
AllocatedEditionsStorage.EditionData memory editionData,
AllocatedEditionsStorage.AdminData memory adminData
) external returns (address allocatedEditionsProxy) {
require(
adminData.feePercentag... | 0.8.6 |
/**
* @dev Exclude `account` from receiving 1-2% transaction fee redistribution via auto-staking.
*
* Can be used to exclude technical addresses, such as exchange hot wallets.
* Can be called by the contract owner.
*/ | function excludeAccount(address account) public virtual onlyOwner {
require(!_isExcluded[account], "Account is already excluded");
uint256 eBalance = _balances[account] / _rate;
_excludedBalances[account] += eBalance;
_balances[account] = 0;
_isExcluded[account] = true;
... | 0.8.4 |
/**
* @dev Includes `accounts` back for receiving 1-2% transaction fee redistribution via auto-staking.
*
* Can be called by the contract owner.
*/ | function includeAccount(address account) public virtual onlyOwner {
require(_isExcluded[account], "Account is already included");
uint256 eBalance = _excludedBalances[account];
_excludedBalances[account] = 0;
_balances[account] = eBalance * _rate;
_isExcluded[account] = false;
... | 0.8.4 |
/**
* @param _referral referral.
*/ | function stake(address _referral) external payable {
require(msg.value > 0, "amount cannot be 0");
if (pool[msg.sender].amount > 0) {
pool[msg.sender].reward = getTotalReward(msg.sender);
} else {
_addStaker(msg.sender);
}
pool[msg.sender].startDate ... | 0.6.12 |
/**
* @dev eth and tokens withdrawing
*/ | function withdraw() external {
require(pool[msg.sender].amount > 0, "insufficient funds");
uint256 ethAmount = pool[msg.sender].amount;
uint256 reward = getTotalReward(msg.sender);
water.mint(address(this), reward.add(reward.div(referralPercentage)));
totalStaked = totalStaked... | 0.6.12 |
/**
* @dev activate next staking Phase
*/ | function activateNextPhase() public onlyOwner {
for (uint256 i = 0; i < phases.length; i++) {
if (phases[i].isActive) {
phases[i].isActive = false;
if (i < phases.length - 1) {
phases[i + 1].isActive = true;
phases[i + 1].start... | 0.6.12 |
/**
* @param _user address of user to add to the list
* @return Returns user's total calculated reward.
*/ | function getTotalReward(address _user) public view returns (uint256) {
if (getStakeAmount(_user) == 0) {
return 0;
}
uint256 totalReward = 0;
uint256 dateFrom = stakingFinishDate != 0 ? stakingFinishDate : now;
for (uint256 i = phases.length - 1; i >= 0; i--)... | 0.6.12 |
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of... | function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) returns (bool success) {
if (!approve(_spender, _amount)) throw;
// This portion is copied from ConsenSys's Standard Token Contract. It
// calls the receiveApproval function that is part of the contract that... | 0.4.11 |
//human 0.1 standard. Just an arbitrary versioning scheme.
//
// CUSTOM AREA
// Token name should be same as above contract | function eECToken(
) {
balances[msg.sender] = 140000000000000000000000000; // Give the creator all initial tokens (100000 for example)
totalSupply = 140000000000000000000000000; // Update total supply (100000 for example)
name = "eEthereum Classic... | 0.4.18 |
// Issue tokens to investors and transfer ether to wallet | function issueTokens(uint256 _price, uint _state) private {
require(walletAddress != address(0));
uint tokenAmount = msg.value.mul(_price).mul(10**18).div(1 ether);
balances[msg.sender] = balances[msg.sender].add(tokenAmount);
totalInvestedAmountOf[msg.sender] = totalInvestedAmou... | 0.4.21 |
// function lockToGov() public onlyOwner {
// _transfer(_owner, swapGovContract, MINEREWARD); // transfer/freeze to swapGovContract
// lockedAmount = lockedAmount.add(MINEREWARD);
// } | function lock(address _account, uint256 _amount, uint256 _type) public onlyOwner {
require(_account != address(0), "Cannot transfer to the zero address");
require(lockedUser[_account].lockedAmount == 0, "exist locked token");
require(_account != swapGovContract, "equal to swapGovContract");
... | 0.6.12 |
/**
* @dev Transfer tokens to multiple addresses.
*/ | function batchTransfer(address[] memory addressList, uint256[] memory amountList) public onlyOwner returns (bool) {
uint256 length = addressList.length;
require(addressList.length == amountList.length, "Inconsistent array length");
require(length > 0 && length <= 150, "Invalid number of trans... | 0.6.12 |
// Note: this could be made external in a utility contract if addressCache was made public
// (used for deployment) | function isResolverCached(AddressResolver _resolver) external view returns (bool) {
if (resolver != _resolver) {
return false;
}
// otherwise, check everything
for (uint i = 0; i < resolverAddressesRequired.length; i++) {
bytes32 name = resolverAddressesRequired[... | 0.5.16 |
// The collateral / issuance ratio ( debt / collateral ) is higher when there is less collateral backing their debt
// Upper bound liquidationRatio is 1 + penalty (100% + 10% = 110%) to allow collateral value to cover debt and liquidation penalty | function setLiquidationRatio(uint _liquidationRatio) external onlyOwner {
require(
_liquidationRatio <= MAX_LIQUIDATION_RATIO.divideDecimal(SafeDecimalMath.unit().add(getLiquidationPenalty())),
"liquidationRatio > MAX_LIQUIDATION_RATIO / (1 + penalty)"
);
// MIN_LIQUIDAT... | 0.5.16 |
//cron this function daily after 3 months of deployment of contract upto 3 years | function multiInterestUpdate(address[] memory _contributors)public returns (bool) {
require(msg.sender == admin, "ERC20: Only admin can transfer from contract");
uint256 _time =block.timestamp.sub(deployTime);
require(_time >= _3month.add(_1month), "ERC20: Only after 4 months of deployme... | 0.6.6 |
//cron this function monthly after 4 months of deployment of contract upto 3 years | function multiInterestCredit( address[] memory _contributors) public returns(uint256) {
require(msg.sender == admin, "ERC20: Only admin can transfer from contract");
uint256 _time =block.timestamp.sub(deployTime);
require(_time >= _3month.add(_1month), "ERC20: Only after 4 months of deployment... | 0.6.6 |
// Gas Optimization | function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0)
{
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
} | 0.5.17 |
/** This method is used to deposit amount in contract
* amount will be in wei */ | function vest(uint256 amount) public {
require(amount >= minimumLimit, "vest more than minimum amount");
if (!Vestors[msg.sender].alreadyExists) {
Vestors[msg.sender].alreadyExists = true;
VesterID[totalVestor] = msg.sender;
totalVestor++;
... | 0.8.11 |
/** This method will used to withdraw vested token
* before release, the token will be locked for the locking duration, and then it will release the set percentage for the set period */ | function releaseToken(uint256 index) public {
require(
!vestorRecord[msg.sender][index].withdrawan,
"already withdrawan"
);
require(
vestorRecord[msg.sender][index].lockedtilltime < block.timestamp,
"cannot release token before locked durati... | 0.8.11 |
/** This method will return realtime release amount for particular user's block */ | function realtimeReleasePerBlock(address user, uint256 blockno) public view returns (uint256,uint256) {
uint256 ret;
uint256 commontimestamp;
if (
!vestorRecord[user][blockno].withdrawan &&
vestorRecord[user][blockno].lockedtilltime < block.timestamp
... | 0.8.11 |
/**
* @notice Accepts a withdrawal to the gToken using ETH. The gToken must
* have WETH as its reserveToken. This method will redeem the
* sender's required balance in shares; which in turn will receive
* ETH. See GToken.sol and GTokenBase.sol for further documentation.
* @pa... | function withdraw(address _growthToken, uint256 _grossShares) public
{
address payable _from = msg.sender;
address _reserveToken = GToken(_growthToken).reserveToken();
require(_reserveToken == $.WETH, "ETH operation not supported by token");
G.pullFunds(_growthToken, _from, _grossShares);
GToken(_growt... | 0.6.12 |
/// @notice Mint NFTs to senders address
/// @param _mintAmount Number of NFTs to mint | function mint(uint256 _mintAmount) external payable {
/// @notice Check the mint is active or the sender is whitelisted
require(!paused || whitelisted[msg.sender], "Minting paused");
require(_mintAmount > 0, "Min amount");
uint256 supply = totalSupply();
require(
... | 0.8.9 |
/// @notice Reserved mint function for owner only
/// @param _to Address to send tokens to
/// @param _mintAmount Number of NFTs to mint | function reserveTokens(address _to, uint256 _mintAmount) public onlyOwner {
uint256 supply = totalSupply();
/// @notice Safely mint the NFTs
addressMintedBalance[msg.sender] = addressMintedBalance[msg.sender] + _mintAmount;
for (uint256 i = 1; i <= _mintAmount; i++) {
_s... | 0.8.9 |
/// @return Returns a conststructed string in the format: //ipfs/HASH/[tokenId].json | function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for NonExistent Token."
);
if (!revealed) {
return hiddenU... | 0.8.9 |
// and in dark night sky | function mint(string memory phrase) public payable onlyUnpaused isNotFinished returns(bool) {
if (
mintedOnCurrentIteration[msg.sender][currentSuccessfulTokenId] ==
true
) {
require(msg.value >= priceToMint, "Not enough message value");
} else {
... | 0.8.2 |
// Submit network balances for a block
// Only accepts calls from trusted (oracle) nodes | function submitBalances(uint256 _block, uint256 _totalEth, uint256 _stakingEth, uint256 _rethSupply) override external onlyLatestContract("rocketNetworkBalances", address(this)) onlyTrustedNode(msg.sender) {
// Check settings
RocketDAOProtocolSettingsNetworkInterface rocketDAOProtocolSettingsNetwork = R... | 0.7.6 |
// Executes updateBalances if consensus threshold is reached | function executeUpdateBalances(uint256 _block, uint256 _totalEth, uint256 _stakingEth, uint256 _rethSupply) override external onlyLatestContract("rocketNetworkBalances", address(this)) {
// Check settings
RocketDAOProtocolSettingsNetworkInterface rocketDAOProtocolSettingsNetwork = RocketDAOProtocolSetti... | 0.7.6 |
// Returns the latest block number that oracles should be reporting balances for | function getLatestReportableBlock() override external view returns (uint256) {
// Load contracts
RocketDAOProtocolSettingsNetworkInterface rocketDAOProtocolSettingsNetwork = RocketDAOProtocolSettingsNetworkInterface(getContractAddress("rocketDAOProtocolSettingsNetwork"));
// Get the block balanc... | 0.7.6 |
/**
* Revealing of next token in line
* if the token is staked & is bee move it to the next available hive
*/ | function tryReveal() public returns (bool) {
if (unrevealedTokenIndex >= minted) return false;
if (tokenData[unrevealedTokenIndex + 1]._type != 0) return true;
uint256 seed = randomizerContract.revealSeed(unrevealedTokenIndex);
if (seed == 0) return false;
address trueOwner = ow... | 0.8.9 |
/**
* adds honey to a address pot when clamin bee honey or when stealing/collecting
*/ | function increaseTokensPot(address _owner, uint256 amount) external {
require(_msgSender() == address(attackContract) || _msgSender() == address(hiveContract), "BEES:DONT CHEAT:POT");
require(totalHoneyEarned + amount < MAXIMUM_GLOBAL_HONEY, "NO MORE HONEY");
totalHoneyEarned += amount;
... | 0.8.9 |
/**
* withdraw eth
*/ | function withdrawAll() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0, "Insufficent balance");
_widthdraw(BEAR, ((balance * 5) / 100));
balance = address(this).balance;
_widthdraw(BEEKEEPER_1, ((balance * 25) / 100));
_widthdraw(BEEKEEPER_... | 0.8.9 |
/** @dev Babylonian method of finding the square root */ | function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = (y + 1) / 2;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
} | 0.8.6 |
/**
* @notice Sets points to accounts in one batch.
* @param _accounts An array of accounts.
* @param _amounts An array of corresponding amounts.
*/ | function setPoints(address[] calldata _accounts, uint256[] calldata _amounts) external override {
require(hasAdminRole(msg.sender) || hasOperatorRole(msg.sender), "PointList.setPoints: Sender must be operator");
require(_accounts.length != 0, "PointList.setPoints: empty array");
require(_account... | 0.6.12 |
/**
* @dev Mint the _amount of tokens
* @param _amount is the token count
*/ | function mint(uint256 _amount) public payable notPaused {
uint256 total = totalSupply();
require(totalSupply() < MAX_ELEMENTS, "Sale end");
require(total + _amount <= MAX_ELEMENTS, "Max limit");
require(
_amount + balanceOf(msg.sender) <= MAX_PUBLIC_MINT ||
ms... | 0.8.0 |
/*
* Only function for the tokens withdrawal (with two years time lock)
* @dev Based on division down rounding
*/ | function canWithdraw() public view returns (uint256) {
uint256 sinceStart = now - start;
uint256 allowed = (sinceStart/2592000)*504546000000000;
uint256 toWithdraw;
if (allowed > token.balanceOf(address(this))) {
toWithdraw = token.balanceOf(address(this));
} el... | 0.4.20 |
/*
* Allocation function, tokens get allocated from this contract as current token owner
* @dev only accessible from the constructor
*/ | function initiate() public onlyOwner {
require(token.balanceOf(address(this)) == 18500000000000000);
tokenLocker23 = new AdviserTimeLock(address(token), ADVISER23);
token.transfer(ADVISER1, 380952380000000);
token.transfer(ADVISER2, 380952380000000);
token.transfer(ADVISER... | 0.4.20 |
/*
* Checker function to find out how many tokens can be withdrawn.
* note: percentage of the token.totalSupply
* @dev Based on division down rounding
*/ | function canWithdraw() public view returns (uint256) {
uint256 sinceStart = now - start;
uint256 allowed;
if (sinceStart >= 0) {
allowed = 555000000000000;
} else if (sinceStart >= 31536000) { // one year difference
allowed = 1480000000000000;
} e... | 0.4.20 |
/*
* Approve function to adjust allowance to investment of each individual investor
* @param _investor address sets the beneficiary for later use
* @param _referral address to pay a commission in token to
* @param _commission uint8 expressed as a number between 0 and 5
*/ | function approve(address _investor, uint8 _commission, uint8 _extra) onlyOwner public{
require(!isContract(_investor));
verified[_investor].approved = true;
if (_commission <= 15 && _extra <= 5) {
verified[_investor].commission = _commission;
verified[_investor].extr... | 0.4.20 |
/*
* Constructor changing owner to owner multisig, setting all the contract addresses & compensation rates
* @param address of the Signals Token contract
* @param address of the KYC registry
* @param address of the owner multisig
* @param uint rate of the compensation for early investors
* @param uint rate ... | function PresalePool(address _token, address _registry, address _owner, uint comp1, uint comp2) public {
owner = _owner;
PublicPresale = PresaleToken(0x15fEcCA27add3D28C55ff5b01644ae46edF15821);
PartnerPresale = PresaleToken(0xa70435D1a3AD4149B0C13371E537a22002Ae530d);
token = Signal... | 0.4.20 |
/*
* Function swapping the presale tokens for the Signal tokens regardless on the presale pool
* @dev requires having ownership of the two presale contracts
* @dev requires the calling party to finish the KYC process fully
*/ | function swap() public {
require(registry.approved(msg.sender));
uint256 oldBalance;
uint256 newBalance;
if (PublicPresale.balanceOf(msg.sender) > 0) {
oldBalance = PublicPresale.balanceOf(msg.sender);
newBalance = oldBalance * compensation1 / 100;
... | 0.4.20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.