comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
// Public Funds Manipulation - withdraw base tokens (as a transfer).
// | function transferBase(uint amountBase) public {
address client = msg.sender;
require(amountBase > 0);
require(amountBase <= balanceBaseForClient[client]);
// overflow safe since we checked less than balance above
balanceBaseForClient[client] -= amountBase;
// we trust the ERC20 token contr... | 0.4.11 |
// Public Funds Manipulation - deposit counter currency (ETH).
// | function depositCntr() public payable {
address client = msg.sender;
uint amountCntr = msg.value;
require(amountCntr > 0);
// overflow safe - if someone owns pow(2,255) ETH we have bigger problems
balanceCntrForClient[client] += amountCntr;
ClientPaymentEvent(client, ClientPaymentEventType... | 0.4.11 |
// Public Funds Manipulation - withdraw counter currency (ETH).
// | function withdrawCntr(uint amountCntr) public {
address client = msg.sender;
require(amountCntr > 0);
require(amountCntr <= balanceCntrForClient[client]);
// overflow safe - checked less than balance above
balanceCntrForClient[client] -= amountCntr;
// safe - not enough gas to do anything ... | 0.4.11 |
// Public Funds Manipulation - deposit previously-approved reward tokens.
// | function transferFromRwrd() public {
address client = msg.sender;
address book = address(this);
uint amountRwrd = rwrdToken.allowance(client, book);
require(amountRwrd > 0);
// we wrote the reward token so we know it supports ERC20 properly and is not evil
require(rwrdToken.transferFrom(cl... | 0.4.11 |
// Public Order View - get full details of an order.
//
// If the orderId does not exist, status will be Unknown.
// | function getOrder(uint128 orderId) public constant returns (
address client, uint16 price, uint sizeBase, Terms terms,
Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr,
uint feesBaseOrCntr, uint feesRwrd) {
Order storage order = orderForOrderId[orderId];
return (order.... | 0.4.11 |
// Public Order View - get mutable details of an order.
//
// If the orderId does not exist, status will be Unknown.
// | function getOrderState(uint128 orderId) public constant returns (
Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr,
uint feesBaseOrCntr, uint feesRwrd) {
Order storage order = orderForOrderId[orderId];
return (order.status, order.reasonCode, order.executedBase, order.execut... | 0.4.11 |
// Public Order View - enumerate all recent orders + all open orders for one client.
//
// Not really designed for use from a smart contract transaction.
//
// Idea is:
// - client ensures order ids are generated so that most-signficant part is time-based;
// - client decides they want all orders after a certain poin... | function walkClientOrders(
address client, uint128 maybeLastOrderIdReturned, uint128 minClosedOrderIdCutoff
) public constant returns (
uint128 orderId, uint16 price, uint sizeBase, Terms terms,
Status status, ReasonCode reasonCode, uint executedBase, uint executedCntr,
uint feesBaseOrC... | 0.4.11 |
// Internal Price Calculation - turn packed price into a friendlier unpacked price.
// | function unpackPrice(uint16 price) internal constant returns (
Direction direction, uint16 mantissa, int8 exponent
) {
uint sidedPriceIndex = uint(price);
uint priceIndex;
if (sidedPriceIndex < 1 || sidedPriceIndex > maxSellPrice) {
direction = Direction.Invalid;
mantissa = 0;
... | 0.4.11 |
// Internal Price Calculation - turn a packed buy price into a packed sell price.
//
// Invalid price remains invalid.
// | function computeOppositePrice(uint16 price) internal constant returns (uint16 opposite) {
if (price < maxBuyPrice || price > maxSellPrice) {
return uint16(invalidPrice);
} else if (price <= minBuyPrice) {
return uint16(maxSellPrice - (price - maxBuyPrice));
} else {
return uint16(max... | 0.4.11 |
// Internal Price Calculation - compute amount in counter currency that would
// be obtained by selling baseAmount at the given unpacked price (if no fees).
//
// Notes:
// - Does not validate price - caller must ensure valid.
// - Could overflow producing very unexpected results if baseAmount very
// large - call... | function computeCntrAmountUsingUnpacked(
uint baseAmount, uint16 mantissa, int8 exponent
) internal constant returns (uint cntrAmount) {
if (exponent < 0) {
return baseAmount * uint(mantissa) / 1000 / 10 ** uint(-exponent);
} else {
return baseAmount * uint(mantissa) / 1000 * 10 ** u... | 0.4.11 |
// Public Order Placement - cancel order
// | function cancelOrder(uint128 orderId) public {
address client = msg.sender;
Order storage order = orderForOrderId[orderId];
require(order.client == client);
Status status = order.status;
if (status != Status.Open && status != Status.NeedsGas) {
return;
}
if (status == Status.Op... | 0.4.11 |
// Public Order Placement - continue placing an order in 'NeedsGas' state
// | function continueOrder(uint128 orderId, uint maxMatches) public {
address client = msg.sender;
Order storage order = orderForOrderId[orderId];
require(order.client == client);
if (order.status != Status.NeedsGas) {
return;
}
order.status = Status.Unknown;
processOrder(orderId, ... | 0.4.11 |
// Internal Order Placement - remove a still-open order from the book.
//
// Caller's job to update/refund the order + raise event, this just
// updates the order chain and bitmask.
//
// Too expensive to do on each resting order match - we only do this for an
// order being cancelled. See matchWithOccupiedPrice for si... | function removeOpenOrderFromBook(uint128 orderId) internal {
Order storage order = orderForOrderId[orderId];
uint16 price = order.price;
OrderChain storage orderChain = orderChainForOccupiedPrice[price];
OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId];
uint128 next... | 0.4.11 |
// Internal Order Placement.
//
// Match our order against up to maxMatches resting orders at the given price (which
// is known by the caller to have at least one resting order).
//
// The matches (partial or complete) of the resting orders are recorded, and their
// funds are credited.
//
// The order chain for the r... | function matchWithOccupiedPrice(
Order storage ourOrder, uint16 theirPrice, uint maxMatches
) internal returns (
bool removedLastAtPrice, uint matchesLeft, MatchStopReason matchStopReason) {
matchesLeft = maxMatches;
uint workingOurExecutedBase = ourOrder.executedBase;
uint workingOurExe... | 0.4.11 |
// Internal Order Placement.
//
// Refund any unmatched funds in an order (based on executed vs size) and move to a final state.
//
// The order is NOT removed from the book by this call and no event is raised.
//
// No sanity checks are made - the caller must be sure the order has not already been refunded.
// | function refundUnmatchedAndFinish(uint128 orderId, Status status, ReasonCode reasonCode) internal {
Order storage order = orderForOrderId[orderId];
uint16 price = order.price;
if (isBuyPrice(price)) {
uint sizeCntr = computeCntrAmountUsingPacked(order.sizeBase, price);
balanceCntrForClient[... | 0.4.11 |
// Internal Order Placement.
//
// Enter a not completely matched order into the book, marking the order as open.
//
// This updates the occupied price bitmap and chain.
//
// No sanity checks are made - the caller must be sure the order
// has some unmatched amount and has been paid for!
// | function enterOrder(uint128 orderId) internal {
Order storage order = orderForOrderId[orderId];
uint16 price = order.price;
OrderChain storage orderChain = orderChainForOccupiedPrice[price];
OrderChainNode storage orderChainNode = orderChainNodeForOpenOrderId[orderId];
if (orderChain.firstOrder... | 0.4.11 |
// Internal Order Placement.
//
// Charge the client for the cost of placing an order in the given direction.
//
// Return true if successful, false otherwise.
// | function debitFunds(
address client, Direction direction, uint sizeBase, uint sizeCntr
) internal returns (bool success) {
if (direction == Direction.Buy) {
uint availableCntr = balanceCntrForClient[client];
if (availableCntr < sizeCntr) {
return false;
}
balanceCnt... | 0.4.11 |
// Internal Book View.
//
// See walkBook - adds up open depth at a price starting from an
// order which is assumed to be open. Careful - unlimited gas use.
// | function sumDepth(uint128 orderId) internal constant returns (uint depth, uint orderCount) {
while (true) {
Order storage order = orderForOrderId[orderId];
depth += order.sizeBase - order.executedBase;
orderCount++;
orderId = orderChainNodeForOpenOrderId[orderId].nextOrderId;
if ... | 0.4.11 |
/**
* @dev Withdraws reward for holder. Returns reward.
*/ | function withdrawReward() public returns (uint256) {
updateTotalReward();
uint256 value = calcReward(msg.sender) + owed[msg.sender];
rewardAtTimeOfWithdraw[msg.sender] = totalReward;
owed[msg.sender] = 0;
require(value > 0, "DevFund: withdrawReward nothing to transfer");
... | 0.6.12 |
/**
* @dev View remaining reward for an address.
* @param forAddress holder's address.
*/ | function rewardFor(address forAddress) public view returns (uint256) {
uint256 _currentBalance = rewardToken.balanceOf(address(this));
uint256 _totalReward = totalReward +
(_currentBalance > prevBalance ? _currentBalance - prevBalance : 0);
return
owed[forAddress] +
... | 0.6.12 |
// /**
// * Transfer tokens
// *
// * Send `_value` tokens to `_to` from your account
// *
// * @param _to The address of the recipient
// * @param _value the amount to send
// */
// function transfer(address _to, uint256 _value) public {
// _transfer(msg.sender, _to, _value);
// } | function transfer (address _to, uint256 _amount) public returns (bool success) {
if( balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
emit Transfer(msg.sender, _to, _a... | 0.4.24 |
/**
@notice Converts country index list into 3 uints
Expects a list of country indexes such that the 2 digit country code is converted to an
index. Countries are expected to be indexed so a "AA" country code is mapped to index 0 and
"ZZ" country is mapped to index 675.
@param countries List of country in... | function convertCountryIndexToBytes(uint[] countries) public pure
returns (uint countries1,uint countries2,uint countries3){
countries1 = 0;
countries2 = 0;
countries3 = 0;
for(uint i = 0; i < countries.length; i++){
uint index = countries[i];
if(... | 0.4.24 |
/**
@notice Add or update a campaign information
Based on a campaign Id (bidId), a campaign can be created (if non existent) or updated.
This function can only be called by the set of allowed addresses registered earlier.
An event will be emited during this function's execution, a CampaignCreated event if th... | function _setCampaign (
bytes32 bidId,
uint price,
uint budget,
uint startDate,
uint endDate,
bool valid,
address owner
)
public
onlyIfWhitelisted("setCampaign",msg.sender) {
CampaignLibrary.Campaign storage campaign = campaigns[bi... | 0.4.24 |
/**
@notice Get a Campaign information
Based on a camapaign Id (bidId), returns all stored information for that campaign.
@param _campaignId Id of the campaign
@return {
"_bidId" : "Id of the campaign",
"_price" : "Value to pay for each proof-of-attention",
"_budget" : "Total value avaliable to be spen... | function getCampaign(bytes32 _campaignId)
public
view
returns (
bytes32 _bidId,
uint _price,
uint _budget,
uint _startDate,
uint _endDate,
bool _valid,
address _campOwner
) {
Campaig... | 0.4.24 |
/**
@notice Upgrade finance contract used by this contract
This function is part of the upgrade mechanism avaliable to the advertisement contracts.
Using this function it is possible to update to a new Advertisement Finance contract without
the need to cancel avaliable campaigns.
Upgrade finance function c... | function upgradeFinance (address addrAdverFinance) public onlyOwner("upgradeFinance") {
BaseFinance newAdvFinance = BaseFinance(addrAdverFinance);
address[] memory devList = advertisementFinance.getUserList();
for(uint i = 0; i < devList.length; i++){
uint balance = a... | 0.4.24 |
/**
@notice Creates a campaign
Method to create a campaign of user aquisition for a certain application.
This method will emit a Campaign Information event with every information
provided in the arguments of this method.
@param packageName Package name of the appication subject to the user aquisition cam... | function _generateCampaign (
string packageName,
uint[3] countries,
uint[] vercodes,
uint price,
uint budget,
uint startDate,
uint endDate)
internal returns (CampaignLibrary.Campaign memory) {
require(budget >= price);
require(e... | 0.4.24 |
/**
@notice Cancel a campaign and give the remaining budget to the campaign owner
When a campaing owner wants to cancel a campaign, the campaign owner needs
to call this function. This function can only be called either by the campaign owner or by
the Advertisement contract owner. This function results in ca... | function cancelCampaign (bytes32 bidId) public {
address campaignOwner = getOwnerOfCampaign(bidId);
// Only contract owner or campaign owner can cancel a campaign
require(owner == msg.sender || campaignOwner == msg.sender);
uint budget = getBudgetOfCampaign(bidId);
advertiseme... | 0.4.24 |
/**
@notice Check if a certain campaign is still valid
Returns a boolean representing the validity of the campaign
Has value of True if the campaign is still valid else has value of False
@param bidId Campaign id to which the query refers
@return { "valid" : "validity of the campaign" }
*/ | function isCampaignValid(bytes32 bidId) public view returns(bool valid) {
uint startDate = advertisementStorage.getCampaignStartDateById(bidId);
uint endDate = advertisementStorage.getCampaignEndDateById(bidId);
bool validity = advertisementStorage.getCampaignValidById(bidId);
uint... | 0.4.24 |
/**
@notice splitSignature
Based on a signature Sig (bytes32), returns the r, s, v
@param sig Signature
@return {
"uint8" : "recover Id",
"bytes32" : "Output of the ECDSA signature",
"bytes32" : "Output of the ECDSA signature",
}
*/ | 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(a... | 0.4.24 |
/**
@notice Sets the Advertisement contract address to allow calls from Advertisement contract
This function is used for upgrading the Advertisement contract without need to redeploy
Advertisement Finance and Advertisement Storage contracts. The function can only be called
by this contract's owner. During ... | function setAllowedAddress (address _addr) public onlyOwner("setAllowedAddress") {
// Verify if the new Ads contract is using the same storage as before
if (allowedAddress != 0x0){
StorageUser storageUser = StorageUser(_addr);
address storageContract = storageUser.getStorage... | 0.4.24 |
/**
@notice Creates an extebded campaign
*/ | function createCampaign (
string packageName,
uint[3] countries,
uint[] vercodes,
uint price,
uint budget,
uint startDate,
uint endDate,
string endPoint)
external
{
CampaignLibrary.Campaign memory newCampaign = _generat... | 0.4.24 |
/**
@notice Function to submit in bulk PoAs
@param bidId Campaign id for which the Proof of attention root hash refferes to
@param rootHash Root hash of all submitted proof of attention to a given campaign
@param signedRootHash Root hash signed by the signing service of the campaign
@param newHashes Number of... | function bulkRegisterPoA(bytes32 bidId, bytes32 rootHash, bytes signedRootHash, uint256 newHashes)
public
onlyIfWhitelisted("createCampaign",msg.sender)
{
/* address addressSig = recoverSigner(rootHash, signedRootHash); */
/* if (msg.sender != addressSig) {
... | 0.4.24 |
/** ========== main functions ========== */ | function mint() external payable nonReentrant returns (uint256) {
require(!userMinted[_msgSender()], "mint: you have claimed one token");
require(usertokenCounters.current() < MAX_AMOUNT_USER, "mint: all tokens have been minted");
// users must pay for the NFT
require(msg.value >=... | 0.8.7 |
/** ========== internal mutative functions ========= */ | function _claim(address receiver) internal {
require(receiver != address(0), "claim: invalid address");
ownertokenCounters.increment();
uint256 mintId = ownertokenCounters.current() + MAX_AMOUNT_USER;
require(mintId > MAX_AMOUNT_USER && mintId <= MAX_AMOUNT, "ownerC... | 0.8.7 |
/// @dev Adds Distribution. This function doesn't limit max gas consumption,
/// so adding too many investors can cause it to reach the out-of-gas error.
/// @param _beneficiary The address of distribution.
/// @param _tokensAllotment The amounts of the tokens that belong to each investor. | function _addDistribution(
address _beneficiary,
DistributionType _distributionType,
uint256 _tokensAllotment
) internal {
require(_beneficiary != address(0), "Invalid address");
require(
_tokensAllotment > 0,
"the investor allocation must be m... | 0.8.0 |
// Check if current block's base fee is under max allowed base fee | function isCurrentBaseFeeAcceptable() public view returns (bool) {
uint256 baseFee;
try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) {
baseFee = currentBaseFee;
} catch {
// Useful for testing until ganache supports london fork
// Ha... | 0.6.12 |
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/ | function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumber == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/... | 0.5.17 |
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (!hasAdminRights()) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
//... | 0.5.17 |
/**
* @notice Accrues interest and reduces Fuse fees by transferring to Fuse
* @param withdrawAmount Amount of fees to withdraw
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function _withdrawFuseFees(uint withdrawAmount) external nonReentrant(false) returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted Fuse fee withdrawal failed.
... | 0.5.17 |
/**
* @notice Reduces Fuse fees by transferring to Fuse
* @dev Requires fresh interest accrual
* @param withdrawAmount Amount of fees to withdraw
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function _withdrawFuseFeesFresh(uint withdrawAmount) internal returns (uint) {
// totalFuseFees - reduceAmount
uint totalFuseFeesNew;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Erro... | 0.5.17 |
/**
* @notice updates the cToken ERC20 name and symbol
* @dev Admin function to update the cToken ERC20 name and symbol
* @param _name the new ERC20 token name to use
* @param _symbol the new ERC20 token symbol to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/ | function _setNameAndSymbol(string calldata _name, string calldata _symbol) external {
// Check caller is admin
require(hasAdminRights(), "caller not admin");
// Set ERC20 name and symbol
name = _name;
symbol = _symbol;
} | 0.5.17 |
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
* Returns the raw returned data... | function _functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.call(data);
if (!success) {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {... | 0.5.17 |
/**
@dev Registers a new contribution, sets their share
@param _sender The address of the wallet contributing
@param _amount The amount that the owner has sent
*/ | function contribute(address _sender, uint256 _amount) private {
require(!locked, "Crowdsale period over, contribution is locked");
require(!distributionActive, "Cannot contribute when distribution is active");
require(_amount >= precisionMinimum, "Amount needs to be above the minimum contribu... | 0.4.24 |
/**
@dev Manually set a share directly, used to set the LinkPool members as owners
@param _owner Wallet address of the owner
@param _value The equivalent contribution value
*/ | function setOwnerShare(address _owner, uint256 _value) public onlyOwner() {
require(!locked, "Can't manually set shares, it's locked");
require(!distributionActive, "Cannot set owners share when distribution is active");
Owner storage o = owners[_owner];
if (o.shareTokens == 0) {
... | 0.4.24 |
/**
@dev Transfer part or all of your ownership to another address
@param _receiver The address that you're sending to
@param _amount The amount of ownership to send, for your balance refer to `ownerShareTokens`
*/ | function sendOwnership(address _receiver, uint256 _amount) public onlyWhitelisted() {
Owner storage o = owners[msg.sender];
Owner storage r = owners[_receiver];
require(o.shareTokens > 0, "You don't have any ownership");
require(o.shareTokens >= _amount, "The amount exceeds what yo... | 0.4.24 |
/**
@dev Start the distribution phase in the contract so owners can claim their tokens
@param _token The token address to start the distribution of
*/ | function distributeTokens(address _token) public onlyWhitelisted() {
require(!distributionActive, "Distribution is already active");
distributionActive = true;
ERC677 erc677 = ERC677(_token);
uint256 currentBalance = erc677.balanceOf(this) - tokenBalance[_token];
require... | 0.4.24 |
/**
@dev Claim tokens by a owner address to add them to their balance
@param _owner The address of the owner to claim tokens for
*/ | function claimTokens(address _owner) public {
Owner storage o = owners[_owner];
Distribution storage d = distributions[totalDistributions];
require(o.shareTokens > 0, "You need to have a share to claim tokens");
require(distributionActive, "Distribution isn't active");
re... | 0.4.24 |
/**
@dev Withdraw tokens from your contract balance
@param _token The token address for token claiming
@param _amount The amount of tokens to withdraw
*/ | function withdrawTokens(address _token, uint256 _amount) public {
require(_amount > 0, "You have requested for 0 tokens to be withdrawn");
Owner storage o = owners[msg.sender];
Distribution storage d = distributions[totalDistributions];
if (distributionActive && !d.claimedAddres... | 0.4.24 |
/**
@dev Credit to Rob Hitchens: https://stackoverflow.com/a/42739843
*/ | function percent(uint numerator, uint denominator, uint precision) private pure returns (uint quotient) {
uint _numerator = numerator * 10 ** (precision+1);
uint _quotient = ((_numerator / denominator) + 5) / 10;
return ( _quotient);
} | 0.4.24 |
//depositRate /1000 | function getDepositRate(uint value, uint day) public view returns(uint){
if(day == 5){
if(value >= 1 * ethWei && value <= 3 * ethWei){
return 8;
}
if(value >= 4 * ethWei && value <= 6 * ethWei){
return 10;
}
if(v... | 0.4.26 |
//shareLevel | function getShareLevel(uint value) public view returns(uint){
if(value >=1 * ethWei && value <=3 * ethWei){
return 1;
}
if(value >=4 * ethWei && value<=6 * ethWei){
return 2;
}
if(value >=7 * ethWei && value <=10 * ethWei){
return 3;
... | 0.4.26 |
//shareRate /100 | function getShareRate(uint level,uint times) public view returns(uint){
if(level == 1 && times == 1){
return 50;
}if(level == 2 && times == 1){
return 50;
}if(level == 2 && times == 2){
... | 0.4.26 |
/*
* manualEpochInit can be used by anyone to initialize an epoch based on the previous one
* This is only applicable if there was no action (deposit/withdraw) in the current epoch.
* Any deposit and withdraw will automatically initialize the current and next epoch.
*/ | function manualEpochInit(address[] memory tokens, uint128 epochId) public whenNotPaused {
require(epochId <= getCurrentEpoch(), "STK:E-306");
for (uint i = 0; i < tokens.length; i++) {
Pool storage p = poolSize[tokens[i]][epochId];
if (epochId == 0) {
p.size = u... | 0.6.12 |
/*
* Returns the valid balance of a user that was taken into consideration in the total pool size for the epoch
* A deposit will only change the next epoch balance.
* A withdraw will decrease the current epoch (and subsequent) balance.
*/ | function getEpochUserBalance(address user, address token, uint128 epochId) public view returns (uint256) {
Checkpoint[] storage checkpoints = balanceCheckpoints[user][token];
// if there are no checkpoints, it means the user never deposited any tokens, so the balance is 0
if (checkpoints.length... | 0.6.12 |
/*
* Returns the total amount of `tokenAddress` that was locked from beginning to end of epoch identified by `epochId`
*/ | function getEpochPoolSize(address tokenAddress, uint128 epochId) public view returns (uint256) {
// Premises:
// 1. it's impossible to have gaps of uninitialized epochs
// - any deposit or withdraw initialize the current epoch which requires the previous one to be initialized
if (epochIs... | 0.6.12 |
/*
* Returns the percentage of time left in the current epoch
*/ | function currentEpochMultiplier() public view returns (uint128) {
uint128 currentEpoch = getCurrentEpoch();
uint256 currentEpochEnd = epoch1Start + currentEpoch * epochDuration;
uint256 timeLeft = currentEpochEnd - block.timestamp;
uint128 multiplier = uint128(timeLeft * BASE_MULTIPLIER ... | 0.6.12 |
/**
* Set new owner for the smart contract.
* May only be called by smart contract owner.
*
* @param _address of new or existing owner of the smart contract
* @param _value boolean stating if the _address should be an owner or not
*/ | function setOwner (address _address, bool _value) public {
require (owners[msg.sender]);
// if removing the _address from owners list, make sure owner is not
// removing himself (which could lead to an ownerless contract).
require (_value == true || _address != msg.sender);
owners[_address] ... | 0.4.21 |
/**
* Initialize the token holders by contract owner
*
* @param _to addresses to allocate token for
* @param _value number of tokens to be allocated
*/ | function initAccounts (address [] _to, uint256 [] _value) public {
require (owners[msg.sender]);
require (_to.length == _value.length);
for (uint256 i=0; i < _to.length; i++){
uint256 amountToAdd;
uint256 amountToSub;
if (_value[i] > accounts[_to[i]]){
... | 0.4.21 |
/**
* @notice Default implementation of verifyTransfer used by SecurityToken
* If the transfer request comes from the STO, it only checks that the investor is in the whitelist
* If the transfer request comes from a token holder, it checks that:
* a) Both are on the whitelist
* b) Seller's sale lockup period i... | function verifyTransfer(address _from, address _to, uint256 /*_amount*/, bytes /* _data */, bool /* _isTransfer */) public returns(Result) {
if (!paused) {
if (allowAllTransfers) {
//All transfers allowed, regardless of whitelist
return Result.VALID;
... | 0.4.24 |
/**
* @notice Adds or removes addresses from the whitelist.
* @param _investor is the address to whitelist
* @param _fromTime is the moment when the sale lockup period ends and the investor can freely sell his tokens
* @param _toTime is the moment when the purchase lockup period ends and the investor can freely... | function modifyWhitelist(
address _investor,
uint256 _fromTime,
uint256 _toTime,
uint256 _expiryTime,
bool _canBuyFromSTO
)
public
withPerm(WHITELIST)
{
//Passing a _time == 0 into this function, is equivalent to removing the _investor fr... | 0.4.24 |
/**
* @notice Adds or removes addresses from the whitelist.
* @param _investors List of the addresses to whitelist
* @param _fromTimes An array of the moment when the sale lockup period ends and the investor can freely sell his tokens
* @param _toTimes An array of the moment when the purchase lockup period ends... | function modifyWhitelistMulti(
address[] _investors,
uint256[] _fromTimes,
uint256[] _toTimes,
uint256[] _expiryTimes,
bool[] _canBuyFromSTO
) public withPerm(WHITELIST) {
require(_investors.length == _fromTimes.length, "Mismatched input lengths");
req... | 0.4.24 |
/**
* @notice Adds or removes addresses from the whitelist - can be called by anyone with a valid signature
* @param _investor is the address to whitelist
* @param _fromTime is the moment when the sale lockup period ends and the investor can freely sell his tokens
* @param _toTime is the moment when the purchas... | function modifyWhitelistSigned(
address _investor,
uint256 _fromTime,
uint256 _toTime,
uint256 _expiryTime,
bool _canBuyFromSTO,
uint256 _validFrom,
uint256 _validTo,
uint256 _nonce,
uint8 _v,
bytes32 _r,
bytes32 _s
... | 0.4.24 |
/**
* @notice Used to verify the signature
*/ | function _checkSig(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal view {
//Check that the signature is valid
//sig should be signing - _investor, _fromTime, _toTime & _expiryTime and be signed by the issuer address
address signer = ecrecover(keccak256(abi.encodePacked("\x19Ethereum... | 0.4.24 |
/// @dev Returns sparse array | function getFundHoldings() external returns (uint[] memory, address[] memory) {
uint[] memory _quantities = new uint[](ownedAssets.length);
address[] memory _assets = new address[](ownedAssets.length);
for (uint i = 0; i < ownedAssets.length; i++) {
address ofAsset = ownedAssets[i];
... | 0.6.1 |
// prices are quoted in DENOMINATION_ASSET so they use denominationDecimals | function calcGav() public returns (uint gav) {
for (uint i = 0; i < ownedAssets.length; ++i) {
address asset = ownedAssets[i];
// assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimals)
uint quantityHeld = assetHoldings(asset);
// Dont bother with the... | 0.6.1 |
/// @notice Reward all fees and perform some updates
/// @dev Anyone can call this | function triggerRewardAllFees()
external
amguPayable(false)
payable
{
updateOwnedAssets();
uint256 gav;
uint256 feesInDenomination;
uint256 feesInShares;
uint256 nav;
(gav, feesInDenomination, feesInShares, nav,,) = performCalculations();
... | 0.6.1 |
/// @dev Check holdings for all assets, and adjust list | function updateOwnedAssets() public {
for (uint i = 0; i < ownedAssets.length; i++) {
address asset = ownedAssets[i];
if (
assetHoldings(asset) == 0 &&
!(asset == address(DENOMINATION_ASSET)) &&
ITrading(routes.trading).getOpenMakeOrdersAga... | 0.6.1 |
/// @dev Just pass if asset not in list | function _removeFromOwnedAssets(address _asset) internal {
if (!isInAssetList[_asset]) { return; }
isInAssetList[_asset] = false;
for (uint i; i < ownedAssets.length; i++) {
if (ownedAssets[i] == _asset) {
ownedAssets[i] = ownedAssets[ownedAssets.length - 1];
... | 0.6.1 |
// admin initiates a request that the insurance fee be changed | function requestChangeInsuranceFees(uint80 _transferFeeNumerator,
uint80 _transferFeeDenominator,
uint80 _mintFeeNumerator,
uint80 _mintFeeDenominator,
uint... | 0.4.19 |
// after a day, beneficiary of a mint request finalizes it by providing the
// index of the request (visible in the MintOperationEvent accompanying the original request) | function finalizeMint(uint index) public onlyAdminOrOwner {
MintOperation memory op = mintOperations[index];
require(op.admin == admin); //checks that the requester's adminship has not been revoked
require(op.deferBlock <= block.number); //checks that enough time has elapsed
address ... | 0.4.19 |
// after a day, admin finalizes the insurance fee change | function finalizeChangeInsuranceFees() public onlyAdminOrOwner {
require(changeInsuranceFeesOperation.admin == admin);
require(changeInsuranceFeesOperation.deferBlock <= block.number);
uint80 _transferFeeNumerator = changeInsuranceFeesOperation._transferFeeNumerator;
uint80 _transfer... | 0.4.19 |
//always removing in renBTC, else use normal method | function removeLiquidityOneCoinThenBurn(bytes calldata _btcDestination, uint256 _token_amounts, uint256 min_amount) external {
uint256 startRenbtcBalance = RENBTC.balanceOf(address(this));
require(curveToken.transferFrom(msg.sender, address(this), _token_amounts));
exchange.remove_liquidity_o... | 0.5.12 |
/**
* @notice Start airdrop
* @param _multiplierPercent Multiplier of the airdrop
*/ | function startAirdrop(uint256 _multiplierPercent) onlyOwner external returns(bool){
pause();
require(multiplierPercent == 0); //This means airdrop was finished
require(_multiplierPercent > PERCENT_DIVIDER); //Require that after airdrop amount of tokens will be greater than b... | 0.4.21 |
/**
* @notice Execute airdrop for a bunch of addresses. Should be repeated for all addresses with non-zero amount of tokens.
* @dev This function can be called by anyone, not only the owner
* @param holders Array of token holder addresses.
* @return true if success
*/ | function drop(address[] holders) external returns(bool){
for(uint256 i=0; i < holders.length; i++){
address holder = holders[i];
if(!isAirdropped(holder)){
uint256 balance = balances[holder];
undropped = undropped.sub(balance);
balanc... | 0.4.21 |
/**
* @param _value the amount of money to burn
*/ | function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit ... | 0.5.5 |
/**
* @param _from the address of the sender
* @param _value the amount of money to burn
*/ | function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; ... | 0.5.5 |
// function testrevenue(address _game) public view returns (uint256, bool, bool, uint256){
// uint256 ethfee;
// uint256 hbfee;
// address local_game = _game;
// IERC721 erc721Address = IERC721(_game);
// for (uint i = 0; i < Games[_game].tokenIdSale.length; i++) {
// uint256 _tokenId = Game... | function revenue() public view returns (uint256, uint){
uint256 ethfee;
uint256 hbfee;
for(uint j = 0; j< arrGames.length; j++) {
address _game = arrGames[j];
IERC721 erc721Address = IERC721(arrGames[j]);
for (uint i = 0; i < Games[_game].tokenIdSale... | 0.5.8 |
/// @notice Enables calling multiple methods in a single call to this contract. | function multicall(bytes[] calldata data) external returns (bytes[] memory results) {
results = new bytes[](data.length);
unchecked {for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
... | 0.8.4 |
/// @notice Enter Meowshi. Deposit xSUSHI `amount`. Mint MEOW for `to`. | function meow(address to, uint256 amount) external returns (uint256 shares) {
ISushiBar(sushiBar).transferFrom(msg.sender, address(bento), amount); // forward to BENTO for skim
(, shares) = bento.deposit(IERC20(sushiBar), address(bento), address(this), amount, 0);
meowMint(to, shares * multip... | 0.8.4 |
// Sets the price for the NFT's | function getHeroPrice() public view returns (uint256) {
uint currentSupply = totalSupply();
if (currentSupply >= 0 && currentSupply < 501){
return 35000000000000000;
}else if(currentSupply >= 501 && currentSupply < 5000){
return 65000000000000000;
}else if(currentSupply >= 5001){
... | 0.8.0 |
// minting function for stakes | function mintForStakers(uint256 numNFTs) public payable onlyRole(STAKER_ROLE){
require(hasSaleStarted, "Sale has not started");
require(stakerSupply > 0, "Staker reserve is empty!");
require(msg.value >= getHeroPrice() * numNFTs, "Incorrect ether value");
require(stakerSupply - numNFTs >= 0, "Exceed... | 0.8.0 |
/**
* @dev Returns the value for `variable` at the indexed sample.
*/ | function getInstantValue(
mapping(uint256 => bytes32) storage samples,
IPriceOracle.Variable variable,
uint256 index
) external view returns (uint256) {
bytes32 sample = samples[index];
_require(sample.timestamp() > 0, Errors.ORACLE_NOT_INITIALIZED);
int256 rawInstan... | 0.7.1 |
/**
* @dev Returns the time average weighted price corresponding to `query`.
*/ | function getTimeWeightedAverage(
mapping(uint256 => bytes32) storage samples,
IPriceOracle.OracleAverageQuery memory query,
uint256 latestIndex
) external view returns (uint256) {
_require(query.secs != 0, Errors.ORACLE_BAD_SECS);
int256 beginAccumulator = getPastAccumulator... | 0.7.1 |
///@notice Add item to progject vote list
/// @dev It must be call from owner before startVote()
/// @param _prjName - string, project name for vote.
/// @param _prjAddress - address, only this address can get
/// reward if project will win. | function addProjectToVote(string calldata _prjName, address _prjAddress)
external
payable
onlyOwner
{
require(currentStage == StageName.preList, "Can't add item after vote has starting!");
require(_prjAddress != address(0),"Address must be valid!");
bytes32 hash = kecca... | 0.5.1 |
///@notice Make vote for sender
/// @dev Sender must send enough ether
/// @param _prjName - string, project name for vote. | function vote(string calldata _prjName) external payable {
require(currentStage == StageName.inProgress,
"Vote disable now!"
);
require(msg.value >= MINETHVOTE, "Please send more ether!");
bytes32 hash = keccak256(bytes(_prjName));
PrjProperties memory... | 0.5.1 |
// Mint weebTEND with TEND | function mint(uint256 amount) public {
require(amount <= TEND.balanceOf(msg.sender), ">TEND.balanceOf");
uint256 totalStakedTendiesBefore = getTotalStakedTendies();
// Stake tendies
TEND.safeTransferFrom(msg.sender, address(this), amount);
uint256 totalStaked... | 0.5.17 |
// Burn weebTEND to get collected TEND | function burn(uint256 amount) public nonReentrant {
require(amount <= balanceOf(msg.sender), ">weebTEND.balanceOf");
// Burn weebTEND
uint256 proRataTend = getTotalStakedTendies().mul(amount).div(totalSupply());
super._burn(msg.sender, amount);
emit Burn(msg.sender... | 0.5.17 |
// Utility function to verify geth style signatures | function verifySig(
address _signer,
bytes32 _theHash,
uint8 _v,
bytes32 _r,
bytes32 _s
) private pure returns (bool) {
bytes32 messageDigest =
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _theHash));
return _signer == ecrecover(messageDigest, _v, _r, _s);
} | 0.6.12 |
// Make a new checkpoint from the supplied validator set
// A checkpoint is a hash of all relevant information about the valset. This is stored by the contract,
// instead of storing the information directly. This saves on storage and gas.
// The format of the checkpoint is:
// h(gravityId, "checkpoint", valsetNonce, v... | function makeCheckpoint(
address[] memory _validators,
uint256[] memory _powers,
uint256 _valsetNonce,
bytes32 _gravityId
) private pure returns (bytes32) {
// bytes32 encoding of the string "checkpoint"
bytes32 methodName = 0x636865636b706f696e7400000000000000000000000000000000000000000000;
by... | 0.6.12 |
// Set root of merkle tree | function setRoot(bytes32 _root) public onlyOwner {
require(address(iEscrowThales) != address(0), "Set Escrow Thales address");
root = _root;
startTime = block.timestamp; //reset time every period
emit NewRoot(_root, block.timestamp, period);
period = period + 1;
} | 0.5.16 |
// Check if a given reward has already been claimed | function claimed(uint256 index) public view returns (uint256 claimedBlock, uint256 claimedMask) {
claimedBlock = _claimed[period][index / 256];
claimedMask = (uint256(1) << uint256(index % 256));
require((claimedBlock & claimedMask) == 0, "Tokens have already been claimed");
} | 0.5.16 |
// Get airdrop tokens assigned to address
// Requires sending merkle proof to the function | function claim(
uint256 index,
uint256 amount,
bytes32[] memory merkleProof
) public notPaused {
// Make sure the tokens have not already been redeemed
(uint256 claimedBlock, uint256 claimedMask) = claimed(index);
_claimed[period][index / 256] = claimedBlock | claimed... | 0.5.16 |
/**
* @notice remove an address from the array
* @dev finds the element, swaps it with the last element, and then deletes it;
* returns a boolean whether the element was found and deleted
* @param self Storage array containing address type variables
* @param element the element to remove from the array
... | function removeAddress(Addresses storage self, address element) internal returns (bool) {
for (uint i = 0; i < self.size(); i++) {
if (self._items[i] == element) {
self._items[i] = self._items[self.size() - 1];
self._items.pop();
return true;
... | 0.6.10 |
/**
* @notice check if an element exist in the array
* @param self Storage array containing address type variables
* @param element the element to check if it exists in the array
*/ | function exists(Addresses storage self, address element) internal view returns (bool) {
for (uint i = 0; i < self.size(); i++) {
if (self._items[i] == element) {
return true;
}
}
return false;
} | 0.6.10 |
/*function deployMinersTest(uint32 _hour, address user, uint32[] area, uint32[] period, uint32[] count) public checkWhiteList payable {
require(area.length > 0);
require(area.length == period.length);
require(area.length == count.length);
address _user = user;
if (_user == address(0)) {
_user = msg.sender;
... | function _deployMiners(address _user, uint32 _hour, uint32[] memory area, uint32[] memory period, uint32[] memory count) internal returns(uint){
uint payment = 0;
uint32 minerCount = 0;
uint32[3][72] storage _areaDeployed = areaHourDeployed[_hour];
uint32[3][72] storage _userAreaDepl... | 0.4.24 |
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/ | function _getTokenAmount(uint256 _weiAmount) internal returns(uint256) {
if ((_weiAmount >= 500000000000000000000) && (_weiAmount < 1000000000000000000000)) {
rate = 7140;
} else if (_weiAmount >= 1000000000000000000000) {
rate = 7650;
} else if (tokensSold <= 214200... | 0.4.23 |
// SO - 50375 | function testStr(string memory str) internal pure returns (bool){
bytes memory b = bytes(str);
if(b.length > 20|| b.length < 1) return false;
for(uint i; i<b.length; i++){
bytes1 ch = b[i];
if(
!(ch >= 0x30 && ch <= 0x39) && //9-0
... | 0.8.7 |
// SO - 58341 | function toAsciiString(address x) internal pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b... | 0.8.7 |
/**
* @dev doubles pruf balance at snapshotID(1)
*/ | function splitMyPruf() external whenNotPaused {
require(
hasSplit[msg.sender] == 0,
"SPLIT:SMP: Caller address has already been split"
);
//^^^^^^^checks^^^^^^^^^
uint256 balanceAtSnapshot = UTIL_TKN.balanceOfAt(msg.sender, 1);
hasSplit[msg.sender] = 170;... | 0.8.0 |
/**
* @dev doubles pruf balance at snapshotID(1)
* @param _address - address to be split
*/ | function splitPrufAtAddress(address _address) external whenNotPaused {
require(
hasSplit[_address] == 0,
"SPLIT:SMPAA: Caller address has already been split"
);
//^^^^^^^checks^^^^^^^^^
uint256 balanceAtSnapshot = UTIL_TKN.balanceOfAt(_address, 1);
hasSpl... | 0.8.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.