comment stringlengths 11 2.99k | function_code stringlengths 165 3.15k | version stringclasses 80
values |
|---|---|---|
/**
* Withdraw tokens emergency.
*
* @param _token Token contract address
* @param _to Address where the token withdraw to
* @param _amount Amount of tokens to withdraw
*/ | function emergencyWithdraw(address _token, address _to, uint256 _amount) external onlyOwner {
IERC20 erc20Token = IERC20(_token);
require(erc20Token.balanceOf(address(this)) > 0, "Insufficient balane");
uint256 amountToWithdraw = _amount;
if (_amount == 0) {
amountToWi... | 0.6.10 |
/**
* Get the reward multiplier over the given _from_block until _to block
*
* @param _fromBlock the start of the period to measure rewards for
* @param _to the end of the period to measure rewards for
*
* @return The weighted multiplier for the given period... | function getMultiplier(uint256 _fromBlock, uint256 _to) public view returns (uint256) {
uint256 _from = _fromBlock >= farmInfo.startBlock ? _fromBlock : farmInfo.startBlock;
uint256 to = farmInfo.endBlock > _to ? _to : farmInfo.endBlock;
if (to <= farmInfo.bonusEndBlock) {
return... | 0.6.10 |
/**
* Function to see accumulated balance of reward token for specified user
*
* @param _user the user for whom unclaimed tokens will be shown
*
* @return total amount of withdrawable reward tokens
*/ | function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint256 accRewardPerShare = farmInfo.accRewardPerShare;
uint256 lpSupply = farmInfo.lpToken.balanceOf(address(this));
if (block.number > farmInfo.lastRewardBlock && lpSupp... | 0.6.10 |
// END ONLY COLLABORATORS | function mint() external payable callerIsUser mintStarted {
require(msg.value >= claimPrice, "Not enough Ether to mint a cube");
require(
claimedTokenPerWallet[msg.sender] < maxClaimsPerWallet,
"You cannot claim more cubes."
);
require(totalMintedTokens ... | 0.8.4 |
/**
* @dev Overrides Crowdsale fund forwarding, sending funds to vault.
*/ | function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
if(!advIsCalc &&_getInStageIndex () > 0 && goalReached() && advWallet != address(0))
{
//Send ETH to advisor, after to stage 1
uint256 advAmount = 0;
advIsCalc = true;
advAmount = weiRaised... | 0.4.21 |
/**
@notice trustee will call the function to approve mint bToken
@param _txid the transaction id of bitcoin
@param _amount the amount to mint, 1BTC = 1bBTC = 1*10**18 weibBTC
@param to mint to the address
*/ | function approveMint(
bytes32 _tunnelKey,
string memory _txid,
uint256 _amount,
address to,
string memory assetAddress
) public override whenNotPaused whenTunnelNotPause(_tunnelKey) onlyTrustee {
if(to == address(0)) {
if (approveFlag[_txid] == fal... | 0.6.12 |
/**
* @dev Set the trust claim (msg.sender trusts subject)
* @param _subject The trusted address
*/ | function trust(address _subject) public onlyVoters {
require(msg.sender != _subject);
require(token != MintableTokenStub(0));
if (!trustRegistry[_subject].trustedBy[msg.sender]) {
trustRegistry[_subject].trustedBy[msg.sender] = true;
trustRegistry[_subject].totalTrust = trustRegistry[_subje... | 0.4.25 |
/**
* @dev Unset the trust claim (msg.sender now reclaims trust from subject)
* @param _subject The address of trustee to revoke trust
*/ | function untrust(address _subject) public onlyVoters {
require(token != MintableTokenStub(0));
if (trustRegistry[_subject].trustedBy[msg.sender]) {
trustRegistry[_subject].trustedBy[msg.sender] = false;
trustRegistry[_subject].totalTrust = trustRegistry[_subject].totalTrust.sub(1);
emit T... | 0.4.25 |
/**
* @dev Proxy function to vote and mint tokens
* @param to The address that will receive the minted tokens.
* @param amount The amount of tokens to mint.
* @param batchCode The detailed information on a batch.
* @return A boolean that indicates if the operation was successful.
*/ | function mint(
address to,
uint256 amount,
string batchCode
)
public
onlyVoters
returns (bool)
{
bytes32 proposalHash = keccak256(abi.encodePacked(to, amount, batchCode));
assert(!mintProposal[proposalHash].executed);
if (!mintProposal[proposalHash].voted[msg.sender]) {
... | 0.4.25 |
/* Transfer an amount from the owner's account to an indicated account */ | function transfer(address _to, uint256 _amount) returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]
&& (! accountHasCurrentVote(msg.sender))) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
... | 0.4.11 |
/* Create a new ballot and set the basic details (proposal description, dates)
* The ballot still need to have options added and then to be sealed
*/ | function adminAddBallot(string _proposal, uint256 _start, uint256 _end) {
/* Admin functions must be called by the contract creator. */
require(msg.sender == m_administrator);
/* Create and store the new ballot objects */
numBallots++;
uint32 ballotId = numBallots;
ballotNames[ballotId... | 0.4.11 |
/* Add an option to an existing Ballot
*/ | function adminAddBallotOption(uint32 _ballotId, string _option) {
/* Admin functions must be called by the contract creator. */
require(msg.sender == m_administrator);
/* verify that the ballot exists */
require(_ballotId > 0 && _ballotId <= numBallots);
/* cannot change a ballot once it ... | 0.4.11 |
//Admin address | function changeAdmin(address newAdmin) public returns (bool) {
require(msg.sender == admin);
require(newAdmin != address(0));
uint256 balAdmin = balances[admin];
balances[newAdmin] = balances[newAdmin].add(balAdmin);
balances[admin] = 0;
admin = newAdmin;
... | 0.4.24 |
/* Amend and option in an existing Ballot
*/ | function adminEditBallotOption(uint32 _ballotId, uint32 _optionId, string _option) {
/* Admin functions must be called by the contract creator. */
require(msg.sender == m_administrator);
/* verify that the ballot exists */
require(_ballotId > 0 && _ballotId <= numBallots);
/* cannot chang... | 0.4.11 |
/* Seal a ballot - after this the ballot is official and no changes can be made.
*/ | function adminSealBallot(uint32 _ballotId) {
/* Admin functions must be called by the contract creator. */
require(msg.sender == m_administrator);
/* verify that the ballot exists */
require(_ballotId > 0 && _ballotId <= numBallots);
/* cannot change a ballot once it is sealed */
if(... | 0.4.11 |
/* function to allow a coin holder add to the vote count of an option in an
* active ballot. The votes added equals the balance of the account. Once this is called successfully
* the coins cannot be transferred out of the account until the end of the ballot.
*
* NB: The timing of the start and end of the voting... | function vote(uint32 _ballotId, uint32 _selectedOptionId) {
/* verify that the ballot exists */
require(_ballotId > 0 && _ballotId <= numBallots);
/* Ballot must be in progress in order to vote */
require(isBallotInProgress(_ballotId));
/* Calculate the balance which which the coin holder... | 0.4.11 |
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome... | function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
... | 0.8.9 |
// Convert an hexadecimal character to their value | function fromHexChar(uint8 c) public pure returns (uint8) {
if (bytes1(c) >= bytes1('0') && bytes1(c) <= bytes1('9')) {
return c - uint8(bytes1('0'));
}
if (bytes1(c) >= bytes1('a') && bytes1(c) <= bytes1('f')) {
return 10 + c - uint8(bytes1('a'));
}
... | 0.7.6 |
// Convert an hexadecimal string to raw bytes | function fromHex(string memory s) public pure returns (bytes memory) {
bytes memory ss = bytes(s);
require(ss.length%2 == 0); // length must be even
bytes memory r = new bytes(ss.length/2);
for (uint i=0; i<ss.length/2; ++i) {
r[i] = bytes1(fromHexChar(uint8(ss[2*i])) * ... | 0.7.6 |
//
// ####################################
//
// tokenholder has to call approve(params: this SC address, amount in uint256)
// method in Token SC, then he/she has to call refund() method in this
// SC, all tokens from amount will be exchanged and the tokenholder will receive
// his/her own ETH on his/her own address | function refund() external {
// First phase
uint256 i = getCurrentPhaseIndex();
require(i == 1 && !phases[i].IS_FINISHED, "Not Allowed phase");
address payable sender = _msgSender();
uint256 value = token.allowance(sender, address(this));
require(value > 0, "Not... | 0.7.6 |
// View function to see pending votess on frontend. | function pendingvotes(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accVotesPerShare = pool.accVotesPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
... | 0.6.12 |
// if somebody accidentally sends tokens to this SC directly you may use
// burnTokensTransferredDirectly(params: tokenholder ETH address, amount in
// uint256) | function refundTokensTransferredDirectly(address payable participant, uint256 value) external selfCall {
uint256 i = getCurrentPhaseIndex();
require(i == 1, "Not Allowed phase");
// First phase
uint256 topay_value = value.mul(_token_exchange_rate).div(10 ** uint256(token.decimals()... | 0.7.6 |
// Deposit LP tokens to VotesPrinter for votes allocation. | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accVotesPerShare).div(1e12).sub(user.rewar... | 0.6.12 |
// Withdraw LP tokens from VotesPrinter. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accVotesPerSh... | 0.6.12 |
/**
* @notice Determine the endBlock based on inputs. Used on the front end to show the exact settings the Farm contract will be deployed with
*/ | function determineEndBlock(uint256 _amount, uint256 _blockReward, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus) public pure returns (uint256, uint256) {
FarmParameters memory params;
params.bonusBlocks = _bonusEndBlock.sub(_startBlock);
params.totalBonusReward = params.bonusBlocks.mul(_bonus)... | 0.6.12 |
/**
* @notice Determine the blockReward based on inputs specifying an end date. Used on the front end to show the exact settings the Farm contract will be deployed with
*/ | function determineBlockReward(uint256 _amount, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus, uint256 _endBlock) public pure returns (uint256, uint256) {
uint256 bonusBlocks = _bonusEndBlock.sub(_startBlock);
uint256 nonBonusBlocks = _endBlock.sub(_bonusEndBlock);
uint256 effectiveBlocks = bon... | 0.6.12 |
/**
* @notice Creates a new FarmUniswap contract and registers it in the
* .sol. All farming rewards are locked in the FarmUniswap Contract
*/ | function createFarmUniswap(IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, IUniFactory _swapFactory, uint256 _blockReward, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus) public onlyOwner returns (address){
require(_startBlock > block.number, 'START'); // ideally at least 24 hours more to give f... | 0.6.12 |
// This is a final distribution after phase 2 is fihished, everyone who left the
// request with register() method will get remaining ETH amount
// in proportion to their exchanged tokens | function startFinalDistribution(uint256 start_index, uint256 end_index) external onlyOwnerOrAdmin {
require(end_index < getNumberOfParticipants());
uint256 j = getCurrentPhaseIndex();
require(j == 3 && !phases[j].IS_FINISHED, "Not Allowed phase");
// Final Phase
... | 0.7.6 |
// this method reverts the current phase to the previous one | function revertPhase() external selfCall {
uint256 i = getCurrentPhaseIndex();
require(i > 0, "Initialize phase is already active");
phases[i].IS_STARTED = false;
phases[i].IS_FINISHED = false;
phases[i - 1].IS_STARTED = true;
phases[i - 1].IS_FINISHED = false... | 0.7.6 |
/* Buying */ | function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(135).div(96);
} else if (_price < increaseLimit3) {
return _price.mul(125).di... | 0.4.21 |
/**
* Create presale contract where lock up period is given days
*/ | function PresaleFundCollector(address _owner, uint _freezeEndsAt, uint _weiMinimumLimit) {
owner = _owner;
// Give argument
if(_freezeEndsAt == 0) {
throw;
}
// Give argument
if(_weiMinimumLimit == 0) {
throw;
}
weiMinimumLimit = _weiMinimumLimit;
freez... | 0.4.8 |
/**
* Participate to a presale.
*/ | function invest() public payable {
// Cannot invest anymore through crowdsale when moving has begun
if(moving) throw;
address investor = msg.sender;
bool existing = balances[investor] > 0;
balances[investor] = balances[investor].plus(msg.value);
// Need to fulfill minimum limit
... | 0.4.8 |
/**
* Load funds to the crowdsale for all investor.
*
*/ | function parcipateCrowdsaleAll() public {
// We might hit a max gas limit in this loop,
// and in this case you can simply call parcipateCrowdsaleInvestor() for all investors
for(uint i=0; i<investors.length; i++) {
parcipateCrowdsaleInvestor(investors[i]);
}
} | 0.4.8 |
/**
* ICO never happened. Allow refund.
*/ | function refund() {
// Trying to ask refund too soon
if(now < freezeEndsAt) throw;
// We have started to move funds
moving = true;
address investor = msg.sender;
if(balances[investor] == 0) throw;
uint amount = balances[investor];
delete balances[investor];
if(!investo... | 0.4.8 |
/**
* @notice initialize the farming contract. This is called only once upon farm creation and the FarmGenerator ensures the farm has the correct paramaters
*/ | function init(
IERC20 _rewardToken,
uint256 _amount,
IERC20 _lpToken,
uint256 _blockReward,
uint256 _startBlock,
uint256 _endBlock,
uint256 _bonusEndBlock,
uint256 _bonus
) public {
address msgSender = _msgSender();
require(msgSender ==... | 0.6.12 |
/**
* @dev Mint pool shares for a given stake amount
* @param _stakeAmount The amount of underlying to stake
* @return shares The number of pool shares minted
*/ | function mint(uint256 _stakeAmount) external returns (uint256 shares) {
require(
stakedToken.allowance(msg.sender, address(this)) >= _stakeAmount,
"mint: insufficient allowance"
);
// Grab the pre-deposit balance and shares for comparison
uint256 oldBalance = stakedToken.balanceOf(address(t... | 0.8.9 |
/**
* @dev Burn some pool shares and claim the underlying tokens
* @param _shareAmount The number of shares to burn
* @return tokens The number of underlying tokens returned
*/ | function burn(uint256 _shareAmount) external returns (uint256 tokens) {
require(balanceOf(msg.sender) >= _shareAmount, "burn: insufficient shares");
// TODO: Extract
// Calculate the user's share of the underlying balance
uint256 balance = stakedToken.balanceOf(address(this));
tokens = (_shareAmoun... | 0.8.9 |
/**
* @notice emergency functoin to withdraw LP tokens and forego harvest rewards. Important to protect users LP tokens
*/ | function emergencyWithdraw() public {
address msgSender = _msgSender();
UserInfo storage user = userInfo[msgSender];
farmInfo.lpToken.safeTransfer(address(msgSender), user.amount);
emit EmergencyWithdraw(msgSender, user.amount);
if (user.amount > 0) {
factory.userLeft... | 0.6.12 |
/**
* @dev Relay an index update that has been signed by an authorized proposer.
* The signature provided must satisfy two criteria:
* (1) the signature must be a valid EIP-712 signature for the proposal; and
* (2) the signer must have the "PROPOSER" role.
* @notice See https://docs.ethers.io/v5/api/signer/#Signer... | function relay(
Proposal calldata relayed,
bytes calldata signature,
address signer
)
external
onlySignedProposals(relayed, signature, signer)
returns (
uint256 bond,
bytes32 proposalId,
uint32 expiresAt
)
{
proposalId = _proposalId(relayed.timestamp, relayed.value,... | 0.8.9 |
/**
* @dev Disputes a proposal prior to its expiration. This causes a bond to be
* posted on behalf of DAOracle stakers and an equal amount to be pulled from
* the caller.
* @notice This actually requests, proposes, and disputes with UMA's SkinnyOO
* which sends the bonds and disputed proposal to UMA's DVM for set... | function dispute(bytes32 proposalId) external {
Proposal storage _proposal = proposal[proposalId];
Index storage _index = index[_proposal.indexId];
require(proposal[proposalId].timestamp != 0, "proposal doesn't exist");
require(
!isDisputed[proposalId] &&
block.timestamp < proposal[propos... | 0.8.9 |
/**
* @dev External callback for UMA's SkinnyOptimisticOracle. Fired whenever a
* disputed proposal has been settled by the DVM, regardless of outcome.
* @notice This is always called by the UMA SkinnyOO contract, not an EOA.
* @param - identifier, ignored
* @param timestamp The timestamp of the proposal
* @param... | function priceSettled(
bytes32, /** identifier */
uint32 timestamp,
bytes calldata ancillaryData,
SkinnyOptimisticOracleInterface.Request calldata request
) external onlyRole(ORACLE) {
bytes32 id = _proposalId(
timestamp,
request.proposedPrice,
bytes32(ancillaryData)
);
P... | 0.8.9 |
/**
* @dev Adds or updates a index. Can only be called by managers.
* @param bondToken The token to be used for bonds
* @param bondAmount The quantity of tokens to offer for bonds
* @param indexId The price index identifier
* @param disputePeriod The proposal dispute window
* @param floor The starting portion of ... | function configureIndex(
IERC20 bondToken,
uint256 bondAmount,
bytes32 indexId,
uint32 disputePeriod,
uint64 floor,
uint64 ceiling,
uint64 tilt,
uint256 drop,
uint64 creatorAmount,
address creatorAddress,
address sponsor
) external onlyRole(MANAGER) {
Index storage _ind... | 0.8.9 |
/**
* @notice handle approvals of tokens that require approving from a base of 0
* @param token - the token we're approving
* @param spender - entity the owner (sender) is approving to spend his tokens
* @param amount - number of tokens being approved
*/ | function safeApprove(IERC20 token, address spender, uint amount) internal returns (bool) {
uint currentAllowance = token.allowance(address(this), spender);
// Do nothing if allowance is already set to this value
if(currentAllowance == amount) {
return true;
}
// If ... | 0.6.12 |
/**
* @notice Create a new CRP
* @dev emits a LogNewCRP event
* @param factoryAddress - the BFactory instance used to create the underlying pool
* @param poolParams - struct containing the names, tokens, weights, balances, and swap fee
* @param rights - struct of permissions, configuring this CRP instance (see abo... | function newCrp(
address factoryAddress,
ConfigurableRightsPool.PoolParams calldata poolParams,
RightsManager.Rights calldata rights
)
external
returns (ConfigurableRightsPool)
{
require(poolParams.constituentTokens.length >= BalancerConstants.MIN_ASSET_LIMIT, "ER... | 0.6.12 |
/**
* @notice Create a new ESP
* @dev emits a LogNewESP event
* @param factoryAddress - the BFactory instance used to create the underlying pool
* @param poolParams - CRP pool parameters
* @param rights - struct of permissions, configuring this CRP instance (see above for definitions)
*/ | function newEsp(
address factoryAddress,
ConfigurableRightsPool.PoolParams calldata poolParams,
RightsManager.Rights calldata rights
)
external
returns (ElasticSupplyPool)
{
require(poolParams.constituentTokens.length >= BalancerConstants.MIN_ASSET_LIMIT, "ERR_TOO... | 0.6.12 |
/**
* Command Hash helper.
*
* Accepts alphanumeric characters, hyphens, periods, and underscores.
* Returns a keccak256 hash of the lowercase command.
*/ | function _commandHash(string memory str) private pure returns (bytes32){
bytes memory b = bytes(str);
for (uint i; i<b.length; i++){
bytes1 char = b[i];
require (
(char >= 0x30 && char <= 0x39) || //0-9
(char >= 0x41 && char <= 0x5A) || //A-Z
(char >= 0x61 && char <= 0x7A) ... | 0.8.7 |
/**
* Update a command.
*
* Requires ownership of token.
*/ | function update(string memory _command, string memory _tokenURI) public {
bytes32 _cmd = _commandHash(_command);
uint tokenID = _commands[_cmd];
require(tokenID > 0, "Command not found.");
require(ownerOf(tokenID) == msg.sender, "Only the owner can update the token.");
require(!_frozen[tokenID], "To... | 0.8.7 |
/**
* Freeze a command.
*
* Requires ownership of token.
*/ | function freeze(string memory _command) public {
bytes32 _cmd = _commandHash(_command);
uint tokenID = _commands[_cmd];
require(tokenID > 0, "Command not found.");
require(ownerOf(tokenID) == msg.sender, "Only the owner can freeze the token.");
require(!_frozen[tokenID], "Already frozen.");
_fr... | 0.8.7 |
// # Minting Helpers | function _safeMintQuantity(address to, uint quantity) private {
uint fromTokenId = _totalMintedCount + 1;
uint toTokenId = _totalMintedCount + quantity + 1;
_totalMintedCount += quantity;
for (uint i = fromTokenId; i < toTokenId; i++) {
_safeMint(to, i);
}
} | 0.8.4 |
// # Sale Mint | function presaleMint(uint[] calldata sacredDevilTokenIds, address to) external
{
uint quantity = sacredDevilTokenIds.length;
_requireNotSoldOut();
require(
// solhint-disable-next-line not-rely-on-time
block.timestamp < PUBLIC_SALE_OPEN_TIME,
"Presale has ended"
);
_requireSaleN... | 0.8.4 |
// Mint new token(s) | function mint(uint8 _quantityToMint) public payable {
require(_startDate <= block.timestamp || (block.timestamp >= _whitelistStartDate && _whitelisted[msg.sender] == true), block.timestamp <= _whitelistStartDate ? "Sale is not open" : "Not whitelisted");
require(_quantityToMint >= 1, "Must mint at lea... | 0.8.3 |
// Withdraw ether from contract | function withdraw() public onlyOwner {
require(address(this).balance > 0, "Balance must be positive");
uint256 _balance = address(this).balance;
address _coldWallet = 0x9781F65af8324b40Ee9Ca421ea963642Bc8a8C2b;
payable(_coldWallet).transfer((_balance * 9)/10);
... | 0.8.3 |
/**
* Same as buy, but explicitly sets your dividend percentage.
* If this has been called before, it will update your `default' dividend
* percentage for regular buy transactions going forward.
*/ | function buyAndSetDivPercentage(address _referredBy, uint8 _divChoice, string providedUnhashedPass)
public
payable
returns (uint)
{
require(icoPhase || regularPhase);
if (icoPhase) {
// Anti-bot measures - not perfect, but should help some.
bytes32 hashedProvidedPass = keccak256... | 0.4.24 |
// Overload | function buyAndTransfer(address _referredBy, address target, bytes _data, uint8 divChoice)
public
payable
{
require(regularPhase);
address _customerAddress = msg.sender;
uint256 frontendBalance = frontTokenBalanceLedger_[msg.sender];
if (userSelectedRate[_customerAddress] && divChoice == 0)... | 0.4.24 |
// Fallback function only works during regular phase - part of anti-bot protection. | function()
payable
public
{
/**
/ If the user has previously set a dividend rate, sending
/ Ether directly to the contract simply purchases more at
/ the most recent rate. If this is their first time, they
/ are automatically placed into the 20% rate `bucket'.
**/
requi... | 0.4.24 |
/**
* Transfer tokens from the caller to a new holder: the Used By Smart Contracts edition.
* No charge incurred for the transfer. No seriously, we'd make a terrible bank.
*/ | function transferFrom(address _from, address _toAddress, uint _amountOfTokens)
public
returns(bool)
{
// Setup variables
address _customerAddress = _from;
bytes memory empty;
// Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens,
// and are tra... | 0.4.24 |
// Get the sell price at the user's average dividend rate | function sellPrice()
public
view
returns(uint)
{
uint price;
if (icoPhase || currentEthInvested < ethInvestedDuringICO) {
price = tokenPriceInitial_;
} else {
// Calculate the tokens received for 100 finney.
// Divide to find the average, to calculate the price.
... | 0.4.24 |
// Get the buy price at a particular dividend rate | function buyPrice(uint dividendRate)
public
view
returns(uint)
{
uint price;
if (icoPhase || currentEthInvested < ethInvestedDuringICO) {
price = tokenPriceInitial_;
} else {
// Calculate the tokens received for 100 finney.
// Divide to find the average, to calculate ... | 0.4.24 |
// Called from transferFrom. Always checks if _customerAddress has dividends. | function withdrawFrom(address _customerAddress)
internal
{
// Setup data
uint _dividends = theDividendsOf(false, _customerAddress);
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends... | 0.4.24 |
/**
* @dev Compute differ payment.
* @param _ethAmount The amount of ETH entitled by the client.
* @param _ethBalance The amount of ETH retained by the payment handler.
* @return The amount of differed ETH payment.
*/ | function computeDifferPayment(uint256 _ethAmount, uint256 _ethBalance) external view returns (uint256) {
if (getPaymentQueue().getNumOfPayments() > 0)
return _ethAmount;
else if (_ethAmount > _ethBalance)
return _ethAmount - _ethBalance; // will never underflow
else
... | 0.4.25 |
/**
* @dev Settle payments by chronological order of registration.
* @param _maxNumOfPayments The maximum number of payments to handle.
*/ | function settlePayments(uint256 _maxNumOfPayments) external {
require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), "settle payments is not authorized");
IETHConverter ethConverter = getETHConverter();
IPaymentHandler paymentHandler = getPaymentHandler();
IPaym... | 0.4.25 |
/**
* @dev Set for what contract this rules are.
*
* @param src20 - Address of src20 contract.
*/ | function setSRC(address src20) override external returns (bool) {
require(doTransferCaller == address(0), "external contract already set");
require(address(_src20) == address(0), "external contract already set");
require(src20 != address(0), "src20 can not be zero");
doTransferCaller... | 0.8.7 |
/**
* @dev Do transfer and checks where funds should go. If both from and to are
* on the whitelist funds should be transferred but if one of them are on the
* grey list token-issuer/owner need to approve transfer.
*
* param from The address to transfer from.
* param to The address to send tokens to.
* @p... | function doTransfer(address from, address to, uint256 value) override external onlyDoTransferCaller returns (bool) {
(from,to,value) = _doTransfer(from, to, value);
if (isChainExists()) {
require(ITransferRules(chainRuleAddr).doTransfer(msg.sender, to, value), "chain doTransfer failed");
... | 0.8.7 |
//---------------------------------------------------------------------------------
// private section
//--------------------------------------------------------------------------------- | function _tryExternalSetSRC(address chainAddr) private returns (bool) {
try ITransferRules(chainAddr).setSRC(_src20) returns (bool) {
return (true);
} catch Error(string memory /*reason*/) {
// This is executed in case
// revert was called inside getData
... | 0.8.7 |
/**
* init internal
*/ | function __SimpleTransferRule_init(
)
internal
initializer
{
__BaseTransferRule_init();
//uniswapV2Pair = 0x03B0da178FecA0b0BBD5D76c431f16261D0A76aa;
uniswapV2Pairs.push(0x03B0da178FecA0b0BBD5D76c431f16261D0A76aa);
_src20 = 0x6Ef5febbD2A56FAb23... | 0.8.7 |
// receive gambler's money and start betting | function () payable {
require(msg.value >= minbet);
require(msg.value <=maxbet);
require(this.balance >= msg.value*2);
luckynum = _getrand09();
if (luckynum < 5) {
uint winvalue = msg.value*2*(10000-190)/10000;
YouWin(msg.sender, msg.value... | 0.4.15 |
/**
* amount that locked up for `addr` in `currentTime`
*/ | function _minimumsGet(
address addr,
uint256 currentTime
)
internal
view
returns (uint256)
{
uint256 minimum = 0;
uint256 c = _minimums[addr].length;
uint256 m;
for (uint256 i=0; i<c; i++) {
i... | 0.8.7 |
// FUNCTIONS | function BOXToken() public {
balances[msg.sender] = TOTAL_SUPPLY;
totalSupply = TOTAL_SUPPLY;
// do the distribution of the token, in token transfer
transfer(WALLET_ECOSYSTEM, ALLOC_ECOSYSTEM);
transfer(WALLET_FOUNDATION, ALLOC_FOUNDATION);
transfer(WALLET_TEAM, A... | 0.4.18 |
// get contributors' locked amount of token
// this lockup will be released in 8 batches which take place every 180 days | function getLockedAmount_contributors(address _contributor)
public
constant
returns (uint256)
{
uint256 countdownDate = contributors_countdownDate[_contributor];
uint256 lockedAmt = contributors_locked[_contributor];
if (now <= countdownDate + (180 * 1 days)) {return locke... | 0.4.18 |
// get investors' locked amount of token
// this lockup will be released in 3 batches:
// 1. on delievery date
// 2. three months after the delivery date
// 3. six months after the delivery date | function getLockedAmount_investors(address _investor)
public
constant
returns (uint256)
{
uint256 delieveryDate = investors_deliveryDate[_investor];
uint256 lockedAmt = investors_locked[_investor];
if (now <= delieveryDate) {return lockedAmt;}
if (now <= delieveryD... | 0.4.18 |
/**
* @dev claims tokens from msg.sender to be converted to tokens on another blockchain
*
* @param _toBlockchain blockchain on which tokens will be issued
* @param _to address to send the tokens to
* @param _amount the amount of tokens to transfer
*/ | function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount) public whenXTransfersEnabled {
// get the current lock limit
uint256 currentLockLimit = getCurrentLockLimit();
// require that; minLimit <= _amount <= currentLockLimit
require(_amount >= minLimit && _amount <= ... | 0.4.26 |
// used to transfer manually when senders are using BTC | function transferToAll(address[] memory tos, uint256[] memory values) public onlyOwner canTradable isActive {
require(
tos.length == values.length
);
for(uint256 i = 0; i < tos.length; i++){
require(_icoSupply >= values[i]);
totalNumberT... | 0.5.3 |
/**
* @dev gets x transfer amount by xTransferId (not txId)
*
* @param _xTransferId unique (if non zero) pre-determined id (unlike _txId which is determined after the transactions been broadcasted)
* @param _for address corresponding to xTransferId
*
* @return amount that was sent in xTransf... | function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256) {
// xTransferId -> txId -> Transaction
Transaction storage transaction = transactions[transactionIds[_xTransferId]];
// verify that the xTransferId is for _for
require(transaction.to == _... | 0.4.26 |
/**
* @dev private method to release tokens held by the contract
*
* @param _to the address to release tokens to
* @param _amount the amount of tokens to release
*/ | function releaseTokens(address _to, uint256 _amount) private {
// get the current release limit
uint256 currentReleaseLimit = getCurrentReleaseLimit();
require(_amount >= minLimit && _amount <= currentReleaseLimit);
// update the previous release limit and block number
... | 0.4.26 |
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that wi... | function transfer(address _to, uint _value) public {
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
if(role[msg.sender] == 2)
{
... | 0.5.3 |
/**
* @notice redeem tokens instantly
* @param tokenAmount amount of token to redeem
* @return true if success
*/ | function instantRedemption(uint256 tokenAmount) external virtual override returns (bool) {
require(tokenAmount > 0, "Token amount must be greater than 0");
uint256 requestDaiAmount = _cadOracle
.cadToDai(tokenAmount.mul(_fixedPriceCADCent))
.div(100);
require(req... | 0.6.8 |
/**
* @notice set the expiry price in the oracle, can only be called by Bot address
* @dev a roundId must be provided to confirm price validity, which is the first Chainlink price provided after the expiryTimestamp
* @param _expiryTimestamp expiry to set a price for
* @param _roundId the first roundId after expiryT... | function setExpiryPriceInOracle(uint256 _expiryTimestamp, uint80 _roundId) external {
(, int256 price, , uint256 roundTimestamp, ) = aggregator.getRoundData(_roundId);
require(_expiryTimestamp <= roundTimestamp, "ChainLinkPricer: roundId not first after expiry");
require(price >= 0, "ChainLinkP... | 0.6.10 |
/**
* @notice get the live price for the asset
* @dev overides the getPrice function in OpynPricerInterface
* @return price of the asset in USD, scaled by 1e8
*/ | function getPrice() external view override returns (uint256) {
(, int256 answer, , , ) = aggregator.latestRoundData();
require(answer > 0, "ChainLinkPricer: price is lower than 0");
// chainlink's answer is already 1e8
return _scaleToBase(uint256(answer));
} | 0.6.10 |
/**
* @notice scale aggregator response to base decimals (1e8)
* @param _price aggregator price
* @return price scaled to 1e8
*/ | function _scaleToBase(uint256 _price) internal view returns (uint256) {
if (aggregatorDecimals > BASE) {
uint256 exp = aggregatorDecimals.sub(BASE);
_price = _price.div(10**exp);
} else if (aggregatorDecimals < BASE) {
uint256 exp = BASE.sub(aggregatorDecimals);
... | 0.6.10 |
/**
* @notice redeem tokens asynchronously
* @param tokenAmount amount of token to redeem
* @return true if success
*/ | function asyncRedemption(uint256 tokenAmount) external virtual override returns (bool) {
require(tokenAmount >= 5e19, "Token amount must be greater than or equal to 50");
AsyncRedemptionRequest memory newRequest = AsyncRedemptionRequest(msg.sender, tokenAmount);
_asyncRequests.push(newReque... | 0.6.8 |
/**
* @notice deposit Dai to faciliate redemptions
* @param maxDaiAmount max amount of Dai to pay for redemptions
* @return true if success
*/ | function capitalize(uint256 maxDaiAmount) external returns (bool) {
uint256 daiAmountRemaining = maxDaiAmount;
uint256 newIndex = _asyncIndex;
uint256 requestLength = _asyncRequests.length;
for (; newIndex < requestLength; newIndex = newIndex.add(1)) {
AsyncRedemptionR... | 0.6.8 |
/**
* @notice see the total token balance awaiting redemptions for a given account
* @dev IMPORTANT this function involves unbounded loop, should NOT be used in critical logical paths
* @param account account that has tokens pending
* @return token amount in 18 decimals
*/ | function tokensPending(address account) external view virtual override returns (uint256) {
uint256 pendingAmount = 0;
uint256 requestLength = _asyncRequests.length;
for (uint256 i = _asyncIndex; i < requestLength; i = i.add(1)) {
AsyncRedemptionRequest storage request = _asyncR... | 0.6.8 |
//gives appropriate number of tokens to purchasing address | function purchaseTokens(address payable playerAddress, uint256 etherValue)
//checks if purchase allowed -- only relevant for limiting actions during setup phase
purchaseAllowed( etherValue )
internal
returns( uint256 )
{
//calculates fee/rewards
uint[2] memory feeAndValue = valueAfter... | 0.5.12 |
// |--------------------------------------|
// [20, 30, 40, 50, 60, 70, 80, 99999999]
// Return reward multiplier over the given _from to _to block. | function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
uint256 result = 0;
if (_from < START_BLOCK) return 0;
for (uint256 i = 0; i < HALVING_AT_BLOCK.length; i++) {
uint256 endBlock = HALVING_AT_BLOCK[i];
if (_to <= endBlock) {
... | 0.6.12 |
// lock 75% of reward if it come from bounus time | function _harvest(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accyodaPerShare).div(1e12).sub(user.rewardDebt);
uint256 masterBal =... | 0.6.12 |
// Deposit LP tokens to yodaMasterFarmer for yoda allocation. | function deposit(uint256 _pid, uint256 _amount) public {
require(_amount > 0, "yodaMasterFarmer::deposit: amount must be greater than 0");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
_harvest(_pid);
... | 0.6.12 |
// Withdraw LP tokens from yodaMasterFarmer. | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "yodaMasterFarmer::withdraw: not good");
updatePool(_pid);
_harvest(_pid);
... | 0.6.12 |
// Claim rewards for Bunnies | function claimRewards(address _contractAddress) public
{
uint256 numStaked = TokensOfOwner[_contractAddress][msg.sender].length;
if (numStaked > 0)
{
uint256 rRate = RewardRate[_contractAddress] * numStaked;
uint256 reward = rRate * ((block.timestamp - lastClaim[_contractAddress][... | 0.8.7 |
// Stake Bunni (deposit ERC721) | function deposit(address _contractAddress, uint256[] calldata tokenIds) external whenNotPaused
{
require(RewardRate[_contractAddress] > 0, "invalid address for staking");
claimRewards(_contractAddress); //Claims All Rewards
uint256 length = tokenIds.length;
for (uint256 i; i < l... | 0.8.7 |
// Unstake Bunni (withdrawal ERC721) | function withdraw(address _contractAddress, uint256[] calldata tokenIds, bool _doClaim) external nonReentrant()
{
if (_doClaim) //You can Withdraw without Claiming if needs be
{
claimRewards(_contractAddress); //Claims All Rewards
}
uint256 length = tokenIds.length;
... | 0.8.7 |
// Returns the current rate of rewards per token (doh) | function rewardPerToken() public view returns (uint256) {
// Do not distribute rewards before games begin
if (block.timestamp < startTime) {
return 0;
}
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
// Effective total supply takes into ac... | 0.6.12 |
// Returns the current reward tokens that the user can claim. | function earned(address account) public view returns (uint256) {
// Each user has it's own effective balance which is just the staked balance multiplied by boost level multiplier.
uint256 effectiveBalance = _balances[account].add(_balancesAccounting[account]);
return effectiveBalance.mul(rewardP... | 0.6.12 |
// Withdraw function to remove stake from the pool | function withdraw(uint256 amount) public override {
require(amount > 0, "Cannot withdraw 0");
updateReward(msg.sender);
uint256 tax = amount.mul(devFee).div(1000);
stakingToken.safeTransfer(devFund, tax);
stakingToken.safeTransfer(msg.sender, amount.sub(tax));
super.wit... | 0.6.12 |
// Called to start the pool with the reward amount it should distribute
// The reward period will be the duration of the pool. | function notifyRewardAmount(uint256 reward) external onlyOwner {
rewardToken.safeTransferFrom(msg.sender, address(this), reward);
updateRewardPerTokenStored();
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = p... | 0.6.12 |
// Notify the reward amount without updating time; | function notifyRewardAmountWithoutUpdateTime(uint256 reward) external onlyOwner {
updateRewardPerTokenStored();
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 le... | 0.6.12 |
// Calculate the cost for purchasing a boost. | function calculateCost(
address _user,
address _token,
uint256 _level
) public view returns (uint256) {
uint256 lastLevel = deflector.getLastTokenLevelForUser(address(this), _token, _user);
if (lastLevel > _level) return 0;
return deflector.getSpendableCostPerTokenFor... | 0.6.12 |
// Purchase a multiplier level, same level cannot be purchased twice. | function purchase(address _token, uint256 _level) external {
require(deflector.isSpendableTokenInContract(address(this), _token), "Not a multiplier token");
uint256 lastLevel = deflector.getLastTokenLevelForUser(address(this), msg.sender, _token);
require(lastLevel < _level, "Cannot downgrade le... | 0.6.12 |
// constructor called during creation of contract | function FuBi() {
owner = msg.sender; // person who deploy the contract will be the owner of the contract
balances[owner] = totalSupply; // balance of owner will be equal to 20000 million
} | 0.4.25 |
// send _amount to each address | function multiSend(address[] _addrs, uint _amount) external payable {
require(_amount > 0);
uint _totalToSend = _amount.mul(_addrs.length);
require(msg.value >= _totalToSend);
// try sending to multiple addresses
uint _totalSent = 0;
for (uint256 i = 0; i < _addrs.length; i++) {
... | 0.4.21 |
/**
* Set basic quarter details for Chainlink Receiver
* @param alpha_token_contract IKladeDiffToken - Klade Alpha Token Contract
* @param omega_token_contract IKladeDifFToken - Klade Omega Token Contract
* @param chainlink_diff_oracle IChainlinkOracle - Chainlink oracle contract that provides difficulty inform... | function set_quarter_details(
IKladeDiffToken alpha_token_contract,
IKladeDiffToken omega_token_contract,
IChainlinkOracle chainlink_diff_oracle,
IChainlinkOracle chainlink_blocknum_oracle,
uint256 required_collateral,
uint256 hedged_revenue,
uint256 miner_... | 0.7.3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.