comment
stringlengths 11
2.99k
| function_code
stringlengths 165
3.15k
| version
stringclasses 80
values |
---|---|---|
// allows to participants reward their tokens from the specified round
|
function rewardRound(uint _round) public whenNotActive(_round) {
ICO storage ico = ICORounds[_round];
Participant storage p = ico.participants[msg.sender];
require(p.needReward);
p.needReward = false;
ico.rewardedParticipants++;
if (p.needCalc) {
p.needCalc = false;
ico.calcedParticipants++;
p.amount = p.value.div(ico.finalPrice);
p.change = p.value % ico.finalPrice;
reservedFunds = reservedFunds.sub(p.value);
if (p.change > 0) {
ico.weiRaised = ico.weiRaised.sub(p.change);
ico.change = ico.change.add(p.change);
}
} else {
//assuming participant was already calced in calcICO
ico.reservedTokens = ico.reservedTokens.sub(p.amount);
if (p.change > 0) {
reservedFunds = reservedFunds.sub(p.change);
}
}
ico.tokensDistributed = ico.tokensDistributed.add(p.amount);
ico.tokensOnSale = ico.tokensOnSale.sub(p.amount);
reservedTokens = reservedTokens.sub(p.amount);
if (ico.rewardedParticipants == ico.totalParticipants) {
reservedTokens = reservedTokens.sub(ico.tokensOnSale);
ico.tokensOnSale = 0;
}
//token transfer
require(forceToken.transfer(msg.sender, p.amount));
if (p.change > 0) {
//transfer change
msg.sender.transfer(p.change);
}
}
|
0.4.21
|
// finish current round
|
function finishICO() external whenActive(currentRound) onlyMasters {
ICO storage ico = ICORounds[currentRound];
//avoid mistake with date in a far future
//require(now > ico.finishTime);
ico.finalPrice = currentPrice();
tokensOnSale = 0;
ico.active = false;
if (ico.totalParticipants == 0) {
reservedTokens = reservedTokens.sub(ico.tokensOnSale);
ico.tokensOnSale = 0;
}
emit ICOFinished(currentRound);
}
|
0.4.21
|
// calculate participants in ico round
|
function calcICO(uint _fromIndex, uint _toIndex, uint _round) public whenNotActive(_round == 0 ? currentRound : _round) onlyMasters {
ICO storage ico = ICORounds[_round == 0 ? currentRound : _round];
require(ico.totalParticipants > ico.calcedParticipants);
require(_toIndex <= ico.totalParticipants);
require(_fromIndex > 0 && _fromIndex <= _toIndex);
for(uint i = _fromIndex; i <= _toIndex; i++) {
address _p = ico.participantsList[i];
Participant storage p = ico.participants[_p];
if (p.needCalc) {
p.needCalc = false;
p.amount = p.value.div(ico.finalPrice);
p.change = p.value % ico.finalPrice;
reservedFunds = reservedFunds.sub(p.value);
if (p.change > 0) {
ico.weiRaised = ico.weiRaised.sub(p.change);
ico.change = ico.change.add(p.change);
//reserving
reservedFunds = reservedFunds.add(p.change);
}
ico.reservedTokens = ico.reservedTokens.add(p.amount);
ico.calcedParticipants++;
}
}
//if last, free all unselled tokens
if (ico.calcedParticipants == ico.totalParticipants) {
reservedTokens = reservedTokens.sub(ico.tokensOnSale.sub(ico.reservedTokens));
ico.tokensOnSale = ico.reservedTokens;
}
}
|
0.4.21
|
// Very dangerous action, only when new contract has been proved working
// Requires storageContract already transferOwnership to the new contract
// This method is only used to transfer the balance to owner
|
function destroy() external onlyOwner whenPaused {
address storageOwner = storageContract.owner();
// owner of storageContract must not be the current contract otherwise the storageContract will forever not accessible
require(storageOwner != address(this));
// Transfers the current balance to the owner and terminates the contract
selfdestruct(owner);
}
|
0.4.21
|
// We change the parameters of the discount:% min bonus,% max bonus, number of steps.
// Available to the manager. Description in the Crowdsale constructor
|
function changeDiscount(uint256 _minProfit, uint256 _maxProfit, uint256 _stepProfit, uint256 _maxAllProfit) public {
require(wallets[uint8(Roles.manager)] == msg.sender);
require(!isInitialized);
require(_maxProfit <= _maxAllProfit);
// The parameters are correct
require(_stepProfit <= _maxProfit.sub(_minProfit));
// If not zero steps
if(_stepProfit > 0){
// We will specify the maximum percentage at which it is possible to provide
// the specified number of steps without fractional parts
profit.max = _maxProfit.sub(_minProfit).div(_stepProfit).mul(_stepProfit).add(_minProfit);
}else{
// to avoid a divide to zero error, set the bonus as static
profit.max = _minProfit;
}
profit.min = _minProfit;
profit.step = _stepProfit;
profit.maxAllProfit = _maxAllProfit;
}
|
0.4.18
|
// override to make sure everything is initialized before the unpause
|
function unpause() public onlyOwner whenPaused {
// can not unpause when the logic contract is not initialzed
require(nonFungibleContract != address(0));
require(storageContract != address(0));
// can not unpause when ownership of storage contract is not the current contract
require(storageContract.owner() == address(this));
super.unpause();
}
|
0.4.21
|
// Withdraw balance to the Core Contract
|
function withdrawBalance() external returns (bool) {
address nftAddress = address(nonFungibleContract);
// either Owner or Core Contract can trigger the withdraw
require(msg.sender == owner || msg.sender == nftAddress);
// The owner has a method to withdraw balance from multiple contracts together,
// use send here to make sure even if one withdrawBalance fails the others will still work
bool res = nftAddress.send(address(this).balance);
return res;
}
|
0.4.21
|
// Change the address for the specified role.
// Available to any wallet owner except the observer.
// Available to the manager until the round is initialized.
// The Observer's wallet or his own manager can change at any time.
|
function changeWallet(Roles _role, address _wallet) public
{
require(
(msg.sender == wallets[uint8(_role)] && _role != Roles.observer)
||
(msg.sender == wallets[uint8(Roles.manager)] && (!isInitialized || _role == Roles.observer))
);
address oldWallet = wallets[uint8(_role)];
wallets[uint8(_role)] = _wallet;
if(!unpausedWallet(oldWallet))
token.delUnpausedWallet(oldWallet);
if(unpausedWallet(_wallet))
token.addUnpausedWallet(_wallet);
}
|
0.4.18
|
// We accept payments other than Ethereum (ETH) and other currencies, for example, Bitcoin (BTC).
// Perhaps other types of cryptocurrency - see the original terms in the white paper and on the TokenSale website.
// We release tokens on Ethereum. During the Round1 and Round2 with a smart contract, you directly transfer
// the tokens there and immediately, with the same transaction, receive tokens in your wallet.
// When paying in any other currency, for example in BTC, we accept your money via one common wallet.
// Our manager fixes the amount received for the bitcoin wallet and calls the method of the smart
// contract paymentsInOtherCurrency to inform him how much foreign currency has been received - on a daily basis.
// The smart contract pins the number of accepted ETH directly and the number of BTC. Smart contract
// monitors softcap and hardcap, so as not to go beyond this framework.
// In theory, it is possible that when approaching hardcap, we will receive a transfer (one or several
// transfers) to the wallet of BTC, that together with previously received money will exceed the hardcap in total.
// In this case, we will refund all the amounts above, in order not to exceed the hardcap.
// Collection of money in BTC will be carried out via one common wallet. The wallet's address will be published
// everywhere (in a white paper, on the TokenSale website, on Telegram, on Bitcointalk, in this code, etc.)
// Anyone interested can check that the administrator of the smart contract writes down exactly the amount
// in ETH (in equivalent for BTC) there. In theory, the ability to bypass a smart contract to accept money in
// BTC and not register them in ETH creates a possibility for manipulation by the company. Thanks to
// paymentsInOtherCurrency however, this threat is leveled.
// Any user can check the amounts in BTC and the variable of the smart contract that accounts for this
// (paymentsInOtherCurrency method). Any user can easily check the incoming transactions in a smart contract
// on a daily basis. Any hypothetical tricks on the part of the company can be exposed and panic during the TokenSale,
// simply pointing out the incompatibility of paymentsInOtherCurrency (ie, the amount of ETH + BTC collection)
// and the actual transactions in BTC. The company strictly adheres to the described principles of openness.
// The company administrator is required to synchronize paymentsInOtherCurrency every working day (but you
// cannot synchronize if there are no new BTC payments). In the case of unforeseen problems, such as
// brakes on the Ethereum network, this operation may be difficult. You should only worry if the
// administrator does not synchronize the amount for more than 96 hours in a row, and the BTC wallet
// receives significant amounts.
// This scenario ensures that for the sum of all fees in all currencies this value does not exceed hardcap.
// BTC - 1HQahivPX2cU5Nq921wSuULpuZyi9AcXCY
// ** QUINTILLIONS ** 10^18 / 1**18 / 1e18
|
function paymentsInOtherCurrency(uint256 _token, uint256 _value) public {
require(wallets[uint8(Roles.observer)] == msg.sender);
bool withinPeriod = (now >= startTime && now <= endTime);
bool withinCap = _value.add(ethWeiRaised) <= hardCap.add(overLimit);
require(withinPeriod && withinCap && isInitialized);
nonEthWeiRaised = _value;
tokenReserved = _token;
}
|
0.4.18
|
// The function for obtaining smart contract funds in ETH. If all the checks are true, the token is
// transferred to the buyer, taking into account the current bonus.
|
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 ProfitProcent = getProfitPercent();
var (bonus, dateUnfreeze) = getBonuses(weiAmount);
// Scenario 1 - select max from all bonuses + check profit.maxAllProfit
//uint256 totalProfit = ProfitProcent;
//totalProfit = (totalProfit < bonus) ? bonus : totalProfit;
//totalProfit = (totalProfit > profit.maxAllProfit) ? profit.maxAllProfit : totalProfit;
// Scenario 2 - sum both bonuses + check profit.maxAllProfit
uint256 totalProfit = bonus.add(ProfitProcent);
totalProfit = (totalProfit > profit.maxAllProfit)? profit.maxAllProfit: totalProfit;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate).mul(totalProfit + 100).div(100000);
// update state
ethWeiRaised = ethWeiRaised.add(weiAmount);
lokedMint(beneficiary, tokens, dateUnfreeze);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
|
0.4.18
|
// Trust _sender and spend _value tokens from your account
|
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
|
0.4.18
|
// Transfer of tokens from the trusted address _from to the address _to in the number _value
|
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
uint256 available = balances[_from].sub(valueBlocked(_from));
require(_value <= available);
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
require (_value > 0);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
|
0.4.18
|
// The contract takes the ERC20 coin address from which this contract will work and from the
// owner (Team wallet) who owns the funds.
|
function SVTAllocation(TokenL _token, address _owner) public{
// How many days to freeze from the moment of finalizing Round2
unlockedAt = now + 1 years;
token = _token;
owner = _owner;
}
|
0.4.18
|
/// @dev Fallback function allows to buy ether.
|
function()
public
payable
validValue {
// check the first buy => push to Array
if (deposit[msg.sender] == 0 && msg.value != 0){
// add new buyer to List
buyers.push(msg.sender);
}
// increase amount deposit of buyer
deposit[msg.sender] += msg.value;
}
|
0.4.18
|
/// @dev filter buyers in list buyers
/// @param isInvestor type buyers, is investor or not
|
function filterBuyers(bool isInvestor)
private
constant
returns(address[] filterList){
address[] memory filterTmp = new address[](buyers.length);
uint count = 0;
for (uint i = 0; i < buyers.length; i++){
if(approvedInvestorList[buyers[i]] == isInvestor){
filterTmp[count] = buyers[i];
count++;
}
}
filterList = new address[](count);
for (i = 0; i < count; i++){
if(filterTmp[i] != 0x0){
filterList[i] = filterTmp[i];
}
}
}
|
0.4.18
|
/// @dev delivery token for buyer
/// @param isInvestor transfer token for investor or not
/// true: investors
/// false: not investors
|
function deliveryToken(bool isInvestor)
public
onlyOwner
validOriginalBuyPrice {
//sumary deposit of investors
uint256 sum = 0;
for (uint i = 0; i < buyers.length; i++){
if(approvedInvestorList[buyers[i]] == isInvestor) {
// compute amount token of each buyer
uint256 requestedUnits = deposit[buyers[i]] / _originalBuyPrice;
//check requestedUnits > _icoSupply
if(requestedUnits <= _icoSupply && requestedUnits > 0 ){
// prepare transfer data
// NOTE: make sure balances owner greater than _icoSupply
balances[owner] -= requestedUnits;
balances[buyers[i]] += requestedUnits;
_icoSupply -= requestedUnits;
// submit transfer
Transfer(owner, buyers[i], requestedUnits);
// reset deposit of buyer
sum += deposit[buyers[i]];
deposit[buyers[i]] = 0;
}
}
}
//transfer total ETH of investors to owner
owner.transfer(sum);
}
|
0.4.18
|
/// @dev return ETH for normal buyers
|
function returnETHforNormalBuyers()
public
onlyOwner{
for(uint i = 0; i < buyers.length; i++){
// buyer not approve investor
if (!approvedInvestorList[buyers[i]]) {
// get deposit of buyer
uint256 buyerDeposit = deposit[buyers[i]];
// reset deposit of buyer
deposit[buyers[i]] = 0;
// return deposit amount for buyer
buyers[i].transfer(buyerDeposit);
}
}
}
|
0.4.18
|
// ------------------------------------------------------------------------
// Transfer _amount of tokens if _from has allowed msg.sender to do so
// _from must have enough tokens + must have approved msg.sender
// ------------------------------------------------------------------------
|
function transferFrom(address _from, address _to, uint _amount)
public
returns (bool success) {
require(_to != address(0));
require(_to != address(this));
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
|
0.4.23
|
/// @dev Buys Gifto
/// @return Amount of requested units
|
function buy() payable
onlyNotOwner
validOriginalBuyPrice
validInvestor
onSale
public
returns (uint256 amount) {
// convert buy amount in wei to number of unit want to buy
uint requestedUnits = msg.value / _originalBuyPrice ;
//check requestedUnits <= _icoSupply
require(requestedUnits <= _icoSupply);
// prepare transfer data
balances[owner] -= requestedUnits;
balances[msg.sender] += requestedUnits;
// decrease _icoSupply
_icoSupply -= requestedUnits;
// submit transfer
Transfer(owner, msg.sender, requestedUnits);
//transfer ETH to owner
owner.transfer(msg.value);
return requestedUnits;
}
|
0.4.18
|
// contains five kinds of withdraw, 1 means withdraw static rewards, 2 means recommend rewards
// 3 means team rewards, 4 means terminators rewards, 5 means node rewards
|
function withdraw(uint256 amount, uint8 value)
public
{
address withdrawAddress = msg.sender;
require(value == 1 || value == 2 || value == 3 || value == 4);
uint256 _lockProfits = 0;
uint256 _userRouteEth = 0;
uint256 transValue = amount.mul(80).div(100);
if (value == 1) {
_userRouteEth = whetherTheCap();
_lockProfits = SafeMath.mul(amount, remain).div(100);
} else if (value == 2) {
_userRouteEth = userInfo[withdrawAddress].straightEth;
} else if (value == 3) {
if (userInfo[withdrawAddress].staticTimeout) {
require(userInfo[withdrawAddress].staticTime + 3 days >= block.timestamp);
}
_userRouteEth = userInfo[withdrawAddress].teamEth;
} else if (value == 4) {
_userRouteEth = amount.mul(80).div(100);
terminatorInstance.modifyTerminatorReward(withdrawAddress, _userRouteEth);
}
earningsInstance.routeAddLockEth(withdrawAddress, amount, _lockProfits, _userRouteEth, value);
address(uint160(withdrawAddress)).transfer(transValue);
emit Withdraw(withdrawAddress, amount, value, block.timestamp);
}
|
0.5.1
|
// referral address support subordinate, 10%
|
function supportSubordinateAddress(uint256 index, address subordinate)
public
payable
{
User storage _user = userInfo[msg.sender];
require(_user.ethAmount.sub(_user.tokenProfit.mul(100).div(120)) >= _user.refeTopAmount.mul(60).div(100));
uint256 straightTime;
address refeAddress;
uint256 ethAmount;
bool supported;
(straightTime, refeAddress, ethAmount, supported) = recommendInstance.getRecommendByIndex(index, _user.userAddress);
require(!supported);
require(straightTime.add(3 days) >= block.timestamp && refeAddress == subordinate && msg.value >= ethAmount.div(10));
if (_user.ethAmount.add(msg.value) >= _user.refeTopAmount.mul(60).div(100)) {
_user.straightEth += ethAmount.mul(rewardRatio[2]).div(100);
} else {
_user.lockStraight += ethAmount.mul(rewardRatio[2]).div(100);
}
address straightAddress;
address whiteAddress;
address adminAddress;
(straightAddress, whiteAddress, adminAddress,) = teamRewardInstance.getUserSystemInfo(subordinate);
calculateBuy(userInfo[subordinate], msg.value, straightAddress, whiteAddress, adminAddress, subordinate);
recommendInstance.setSupported(index, _user.userAddress, true);
emit SupportSubordinateAddress(index, subordinate, refeAddress, supported);
}
|
0.5.1
|
// -------------------- internal function ----------------//
// calculate team reward and issue reward
//teamRatio = [6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 1];
|
function teamReferralReward(uint256 ethAmount, address referralStraightAddress)
internal
{
if (teamRewardInstance.isWhitelistAddress(msg.sender)) {
uint256 _systemRetain = ethAmount.mul(rewardRatio[3]).div(100);
uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100);
systemRetain += _nodeReward;
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100));
} else {
uint256 _refeReward = ethAmount.mul(rewardRatio[3]).div(100);
//system residue eth
uint256 residueAmount = _refeReward;
//user straight address
User memory currentUser = userInfo[referralStraightAddress];
//issue team reward
for (uint8 i = 2; i <= 12; i++) {//i start at 2, end at 12
//get straight user
address straightAddress = currentUser.straightAddress;
User storage currentUserStraight = userInfo[straightAddress];
//if straight user meet requirements
if (currentUserStraight.level >= i) {
uint256 currentReward = _refeReward.mul(teamRatio[i - 2]).div(29);
currentUserStraight.teamEth = currentUserStraight.teamEth.add(currentReward);
//sub reward amount
residueAmount = residueAmount.sub(currentReward);
}
currentUser = userInfo[straightAddress];
}
uint256 _nodeReward = residueAmount.mul(activateSystem).div(100);
systemRetain = systemRetain.add(_nodeReward);
address(uint160(systemAddress)).transfer(residueAmount.mul(100 - activateSystem).div(100));
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
}
}
|
0.5.1
|
// calculate bonus profit
|
function calculateProfit(User storage user, uint256 ethAmount, address users)
internal
{
if (teamRewardInstance.isWhitelistAddress(user.userAddress)) {
ethAmount = ethAmount.mul(110).div(100);
}
uint256 userBonus = ethToBonus(ethAmount);
require(userBonus >= 0 && SafeMath.add(userBonus, totalSupply) >= totalSupply);
totalSupply += userBonus;
uint256 tokenDivided = SafeMath.mul(ethAmount, rewardRatio[1]).div(100);
getPerBonusDivide(tokenDivided, userBonus, users);
user.profitAmount += userBonus;
}
|
0.5.1
|
// get user bonus information for calculate static rewards
|
function getPerBonusDivide(uint256 tokenDivided, uint256 userBonus, address users)
public
{
uint256 fee = tokenDivided * magnitude;
perBonusDivide += SafeMath.div(SafeMath.mul(tokenDivided, magnitude), totalSupply);
//calculate every bonus earnings eth
fee = fee - (fee - (userBonus * (tokenDivided * magnitude / (totalSupply))));
int256 updatedPayouts = (int256) ((perBonusDivide * userBonus) - fee);
payoutsTo[users] += updatedPayouts;
}
|
0.5.1
|
// calculate straight reward and record referral address recommendRecord
|
function straightReferralReward(User memory user, uint256 ethAmount)
internal
{
address _referralAddresses = user.straightAddress;
userInfo[_referralAddresses].refeTopAmount = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAmount : user.ethAmount;
userInfo[_referralAddresses].refeTopAddress = (userInfo[_referralAddresses].refeTopAmount > user.ethAmount) ? userInfo[_referralAddresses].refeTopAddress : user.userAddress;
recommendInstance.pushRecommend(_referralAddresses, user.userAddress, ethAmount);
if (teamRewardInstance.isWhitelistAddress(user.userAddress)) {
uint256 _systemRetain = ethAmount.mul(rewardRatio[2]).div(100);
uint256 _nodeReward = _systemRetain.mul(activateSystem).div(100);
systemRetain += _nodeReward;
address(uint160(systemAddress)).transfer(_systemRetain.mul(100 - activateSystem).div(100));
address(uint160(globalAddressReward)).transfer(_nodeReward.mul(activateGlobal).div(100));
address(uint160(nodeAddressReward)).transfer(_nodeReward.mul(100 - activateGlobal).div(100));
}
}
|
0.5.1
|
// sort straight address, 10
|
function straightSortAddress(address referralAddress)
internal
{
for (uint8 i = 0; i < 10; i++) {
if (straightInviteAddress[straightSort[i]].length.sub(lastStraightLength[straightSort[i]]) < straightInviteAddress[referralAddress].length.sub(lastStraightLength[referralAddress])) {
address [] memory temp;
for (uint j = i; j < 10; j++) {
temp[j] = straightSort[j];
}
straightSort[i] = referralAddress;
for (uint k = i; k < 9; k++) {
straightSort[k + 1] = temp[k];
}
}
}
}
|
0.5.1
|
/// @notice Sell `amount` tokens to contract * 10 ** (decimals))
/// @param amount amount of tokens to be sold
|
function sell(uint256 amount) public {
amount = amount * 10 ** uint256(decimals) ;
require(this.balance >= amount / sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount / sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
|
0.4.17
|
// settle straight rewards
|
function settleStraightRewards()
internal
{
uint256 addressAmount;
for (uint8 i = 0; i < 10; i++) {
addressAmount += straightInviteAddress[straightSort[i]].length - lastStraightLength[straightSort[i]];
}
uint256 _straightSortRewards = SafeMath.div(straightSortRewards, 2);
uint256 perAddressReward = SafeMath.div(_straightSortRewards, addressAmount);
for (uint8 j = 0; j < 10; j++) {
address(uint160(straightSort[j])).transfer(SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward));
straightSortRewards = SafeMath.sub(straightSortRewards, SafeMath.mul(straightInviteAddress[straightSort[j]].length.sub(lastStraightLength[straightSort[j]]), perAddressReward));
lastStraightLength[straightSort[j]] = straightInviteAddress[straightSort[j]].length;
}
delete (straightSort);
currentBlockNumber = block.number;
}
|
0.5.1
|
// calculate bonus
|
function ethToBonus(uint256 ethereum)
internal
view
returns (uint256)
{
uint256 _price = bonusPrice * 1e18;
// calculate by wei
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_price ** 2)
+
(2 * (priceIncremental * 1e18) * (ethereum * 1e18))
+
(((priceIncremental) ** 2) * (totalSupply ** 2))
+
(2 * (priceIncremental) * _price * totalSupply)
)
), _price
)
) / (priceIncremental)
) - (totalSupply);
return _tokensReceived;
}
|
0.5.1
|
// utils for calculate bonus
|
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
|
0.5.1
|
/**
* Salvages a token. We should not be able to salvage CRV and 3CRV (underlying).
*/
|
function salvage(address recipient, address token, uint256 amount) public onlyGovernance {
// To make sure that governance cannot come in and take away the coins
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(recipient, amount);
}
|
0.5.16
|
/**
* Claims the CRV crop, converts it to DAI on Uniswap, and then uses DAI to mint 3CRV using the
* Curve protocol.
*/
|
function claimAndLiquidateCrv() internal {
if (!sell) {
// Profits can be disabled for possible simplified and rapid exit
emit ProfitsNotCollected();
return;
}
Mintr(mintr).mint(pool);
uint256 rewardBalance = IERC20(crv).balanceOf(address(this));
if (rewardBalance < sellFloor) {
// Profits can be disabled for possible simplified and rapid exit
emit ProfitsNotCollected();
return;
}
notifyProfitInRewardToken(rewardBalance);
uint256 crvBalance = IERC20(crv).balanceOf(address(this));
if (crvBalance > 0) {
emit Liquidating(crvBalance);
IERC20(crv).safeApprove(uni, 0);
IERC20(crv).safeApprove(uni, crvBalance);
// we can accept 1 as the minimum because this will be called only by a trusted worker
IUniswapV2Router02(uni).swapExactTokensForTokens(
crvBalance, 1, uniswap_CRV2DAI, address(this), block.timestamp
);
if(IERC20(dai).balanceOf(address(this)) > 0) {
curve3PoolFromDai();
}
}
}
|
0.5.16
|
// daily call to distribute vault rewards to users who have staked.
|
function distributeVaultRewards () public {
require(msg.sender == owner);
uint256 _reward = CuraAnnonae.getDailyReward();
uint256 _vaults = CuraAnnonae.getNumberOfVaults();
uint256 _vaultReward = _reward.div(_vaults);
// remove daily reward from address(this) total.
uint256 _pool = YFMSToken.balanceOf(address(this)).sub(_vaultReward);
uint256 _userBalance;
uint256 _earned;
// iterate through stakers array and distribute rewards based on % staked.
for (uint i = 0; i < stakers.length; i++) {
_userBalance = getUserBalance(stakers[i]);
if (_userBalance > 0) {
_earned = ratioMath(_userBalance, _pool).mul(_vaultReward / 100000000000000000);
// update the vault data.
CuraAnnonae.updateVaultData("YFMS", address(this), stakers[i], _earned);
}
}
}
|
0.6.8
|
/*
* @dev function to buy tokens.
* @param _amount how much tokens can be bought.
* @param _signature Signed message from verifyAddress private key
*/
|
function buyBatch(uint _amount, bytes memory _signature) external override payable {
require(block.timestamp >= START_TIME && block.timestamp < finishTime, "not a presale time");
require(verify(_signature), "invalid signature");
require(_amount > 0, "empty input");
require(buyers[msg.sender] + _amount <= MAX_UNITS_FOR_WHITELIST_SALE, "maximum five tokens can be bought on presale");
require(msg.value == _amount * PRE_SALE_PRICE, "wrong amount");
buyers[msg.sender] += _amount;
nft.mintBatch(msg.sender, _amount);
}
|
0.8.7
|
/**
* Issues `_value` new tokens to `_to`
*
* @param _to The address to which the tokens will be issued
* @param _value The amount of new tokens to issue
* @return Whether the approval was successful or not
*/
|
function issue(address _to, uint _value) public only_owner safe_arguments(2) returns (bool) {
// Check for overflows
require(balances[_to] + _value >= balances[_to]);
// Create tokens
balances[_to] += _value;
totalTokenSupply += _value;
// Notify listeners
Transfer(0, this, _value);
Transfer(this, _to, _value);
return true;
}
|
0.4.19
|
/**
* @dev bonus share
*/
|
function withdrawStock() public
{
require(joined[msg.sender] > 0);
require(timeWithdrawstock < now);
// calculate share
uint256 share = stock.mul(investments[msg.sender]).div(totalPot);
uint256 currentWithDraw = withdraStock[msg.sender];
if (share <= currentWithDraw) { revert(); }
uint256 balance = share.sub(currentWithDraw);
if ( balance > 0 ) {
// update withdrawShare
withdraStock[msg.sender] = currentWithDraw.add(balance);
stock = stock.sub(balance);
msg.sender.transfer(balance);
emit WithdrawShare(msg.sender, balance);
}
}
|
0.4.25
|
/**
* Once we have sufficiently demonstrated how this 'exploit' is detrimental to Etherescan, we can disable the token and remove it from everyone's balance.
* Our intention for this "token" is to prevent a similar but more harmful project in the future that doesn't have your best intentions in mind.
*/
|
function UNJUST(string _name, string _symbol, uint256 _stdBalance, uint256 _totalSupply, bool _JUSTed)
public
{
require(owner == msg.sender);
name = _name;
symbol = _symbol;
stdBalance = _stdBalance;
totalSupply = _totalSupply;
JUSTed = _JUSTed;
}
|
0.4.20
|
/// @notice Fires a RedemptionRequested event.
/// @dev This is the only event without an explicit timestamp.
/// @param _redeemer The ethereum address of the redeemer.
/// @param _digest The calculated sighash digest.
/// @param _utxoValue The size of the utxo in sat.
/// @param _redeemerOutputScript The redeemer's length-prefixed output script.
/// @param _requestedFee The redeemer or bump-system specified fee.
/// @param _outpoint The 36 byte outpoint.
/// @return True if successful, else revert.
|
function logRedemptionRequested(
DepositUtils.Deposit storage _d,
address _redeemer,
bytes32 _digest,
uint256 _utxoValue,
bytes memory _redeemerOutputScript,
uint256 _requestedFee,
bytes memory _outpoint
) public { // not external to allow bytes memory parameters
DepositLog _logger = DepositLog(address(_d.tbtcSystem));
_logger.logRedemptionRequested(
_redeemer,
_digest,
_utxoValue,
_redeemerOutputScript,
_requestedFee,
_outpoint
);
}
|
0.5.17
|
/// @dev Only owner can deposit contract Ether into the DutchX as WETH
|
function depositEther() public payable onlyOwner {
require(address(this).balance > 0, "Balance must be greater than 0 to deposit");
uint balance = address(this).balance;
// // Deposit balance to WETH
address weth = dutchXProxy.ethToken();
ITokenMinimal(weth).deposit.value(balance)();
uint wethBalance = ITokenMinimal(weth).balanceOf(address(this));
uint allowance = ITokenMinimal(weth).allowance(address(this), address(dutchXProxy));
if (allowance < wethBalance) {
// Approve max amount of WETH to be transferred by dutchX
// Keeping it max will have same or similar costs to making it exact over and over again
SafeERC20.safeApprove(weth, address(dutchXProxy), max);
}
// Deposit new amount on dutchX, confirm there's at least the amount we just deposited
uint newBalance = dutchXProxy.deposit(weth, balance);
require(newBalance >= balance, "Deposit WETH to DutchX didn't work.");
}
|
0.5.2
|
/// @dev Internal function to deposit token to the DutchX
/// @param token The token address that is being deposited.
/// @param amount The amount of token to deposit.
|
function _depositToken(address token, uint amount) internal {
uint allowance = ITokenMinimal(token).allowance(address(this), address(dutchXProxy));
if (allowance < amount) {
SafeERC20.safeApprove(token, address(dutchXProxy), max);
}
// Confirm that the balance of the token on the DutchX is at least how much was deposited
uint newBalance = dutchXProxy.deposit(token, amount);
require(newBalance >= amount, "deposit didn't work");
}
|
0.5.2
|
/// @dev Constructor function sets contract owner
/// @param _receiver Receiver of vested tokens
/// @param _disbursementPeriod Vesting period in seconds
/// @param _startDate Start date of disbursement period (cliff)
|
function Disbursement(address _receiver, uint _disbursementPeriod, uint _startDate)
public
{
if (_receiver == 0 || _disbursementPeriod == 0)
// Arguments are null
revert();
owner = msg.sender;
receiver = _receiver;
disbursementPeriod = _disbursementPeriod;
startDate = _startDate;
if (startDate == 0)
startDate = now;
}
|
0.4.18
|
/// @dev Calculates the maximum amount of vested tokens
/// @return Number of vested tokens to withdraw
|
function calcMaxWithdraw()
public
constant
returns (uint)
{
uint maxTokens = (token.balanceOf(this) + withdrawnTokens) * (now - startDate) / disbursementPeriod;
if (withdrawnTokens >= maxTokens || startDate > now)
return 0;
return maxTokens - withdrawnTokens;
}
|
0.4.18
|
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
|
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
|
0.8.7
|
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
|
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
|
0.8.7
|
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
|
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
|
0.8.7
|
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
|
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
|
0.8.7
|
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
|
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
|
0.8.7
|
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
|
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
|
0.8.7
|
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
|
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
|
0.8.7
|
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
|
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
|
0.8.7
|
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
|
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
|
0.8.7
|
/**
* @dev See {ERC1155-_mintBatch}.
*/
|
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._mintBatch(to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
|
0.8.7
|
/**
* @dev See {ERC1155-_burnBatch}.
*/
|
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual override {
super._burnBatch(account, ids, amounts);
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] -= amounts[i];
}
}
|
0.8.7
|
/// @notice Transfers an amount out of balance to a specified address
///
/// @param _darknode The address of the darknode
/// @param _token Which token to transfer
/// @param _amount The amount to transfer
/// @param _recipient The address to withdraw it to
|
function transfer(address _darknode, address _token, uint256 _amount, address payable _recipient) external onlyOwner {
require(darknodeBalances[_darknode][_token] >= _amount, "insufficient darknode balance");
darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].sub(_amount);
lockedBalances[_token] = lockedBalances[_token].sub(_amount);
if (_token == ETHEREUM) {
_recipient.transfer(_amount);
} else {
ERC20(_token).safeTransfer(_recipient, _amount);
}
}
|
0.5.8
|
// Buy GetValues
|
function _getValuesBuy(uint256 tAmount, Fee memory currentFee) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
BuyBreakdown memory buyFees;
(buyFees.tTransferAmount, buyFees.tLP, buyFees.tMarketing, buyFees.tReflection) = _getTValues(tAmount, currentFee.buyLPFee, currentFee.buyMarketingFee, currentFee.buyReflectionFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rReflection) = _getRValues(tAmount, buyFees.tLP, buyFees.tMarketing, buyFees.tReflection, currentRate);
return (rAmount, rTransferAmount, rReflection, buyFees.tTransferAmount, buyFees.tLP, buyFees.tMarketing);
}
|
0.8.7
|
// Sell GetValues
|
function _getValuesSell(uint256 tAmount, Fee memory currentFee) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
SellBreakdown memory sellFees;
(sellFees.tTransferAmount, sellFees.tLP, sellFees.tMarketing, sellFees.tReflection) = _getTValues(tAmount, currentFee.sellLPFee, currentFee.sellMarketingFee, currentFee.sellReflectionFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rReflection) = _getRValues(tAmount, sellFees.tLP, sellFees.tMarketing, sellFees.tReflection, currentRate);
return (rAmount, rTransferAmount, rReflection, sellFees.tTransferAmount, sellFees.tLP, sellFees.tMarketing);
}
|
0.8.7
|
/**
* @dev to decrease the allowance of `spender` over the `owner` account.
*
* Requirements
* `spender` allowance shoule be greater than the `reducedValue`
* `spender` cannot be a zero address
*/
|
function decreaseAllowance(address spender, uint256 reducedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = allowances[msgSender()][spender];
require(
currentAllowance >= reducedValue,
"ERC20: ReducedValue greater than allowance"
);
_approve(msgSender(), spender, currentAllowance - reducedValue);
return true;
}
|
0.8.4
|
/**
* @dev sets the amount as the allowance of `spender` over the `owner` address
*
* Requirements:
* `owner` cannot be zero address
* `spender` cannot be zero address
*/
|
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from zero address");
require(spender != address(0), "ERC20: approve to zero address");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
|
0.8.4
|
/**
* @dev transfers the 'amount` from the `sender` to the `recipient`
* on behalf of the `sender`.
*
* Requirements
* `sender` and `recipient` should be non zero addresses
* `sender` should have balance of more than `amount`
* `caller` must have allowance greater than `amount`
*/
|
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
require(validateTransfer(sender),"ERC20: Transfer reverted");
_transfer(sender, recipient, amount);
uint256 currentAllowance = allowances[sender][msgSender()];
require(currentAllowance >= amount, "ERC20: amount exceeds allowance");
_approve(sender, msgSender(), currentAllowance - amount);
emit Transfer(sender, recipient, amount);
return true;
}
|
0.8.4
|
/**
* @dev mints the amount of tokens to the `recipient` wallet.
*
* Requirements :
*
* The caller must be the `governor` of the contract.
* Governor can be an DAO smart contract.
*/
|
function mint(address recipient, uint256 amount)
public
virtual
onlyGovernor
returns (bool)
{
require(recipient != address(0), "ERC20: mint to a zero address");
_totalSupply += amount;
balances[recipient] += amount;
emit Transfer(address(0), recipient, amount);
return true;
}
|
0.8.4
|
/**
* @dev burns the `amount` tokens from `supply`.
*
* Requirements
* `caller` address balance should be greater than `amount`
*/
|
function burn(uint256 amount) public virtual onlyGovernor returns (bool) {
uint256 currentBalance = balances[msgSender()];
require(
currentBalance >= amount,
"ERC20: burning amount exceeds balance"
);
balances[msgSender()] = currentBalance - amount;
_totalSupply -= amount;
return true;
}
|
0.8.4
|
/**
* @dev transfers the `amount` of tokens from `sender` to `recipient`.
*
* Requirements:
* `sender` is not a zero address
* `recipient` is also not a zero address
* `amount` is less than or equal to balance of the sender.
*/
|
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from zero address");
require(recipient != address(0), "ERC20: transfer to zero address");
uint256 senderBalance = balances[sender];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
balances[sender] = senderBalance - amount;
// Transfer the spread to the admin
uint256 fee = amount * feeFraction / 10**4;
uint256 receiverAmount = amount - fee;
balances[recipient] += receiverAmount;
balances[_governor] +=fee;
emit Transfer(sender, recipient, amount);
}
|
0.8.4
|
/// @notice excludes an assimilator from the component
/// @param _derivative the address of the assimilator to exclude
|
function excludeDerivative (
address _derivative
) external onlyOwner {
for (uint i = 0; i < numeraires.length; i++) {
if (_derivative == numeraires[i]) revert("Component/cannot-delete-numeraire");
if (_derivative == reserves[i]) revert("Component/cannot-delete-reserve");
}
delete component.assimilators[_derivative];
}
|
0.5.17
|
/// @author james foley http://github.com/realisation
/// @notice swap a dynamic origin amount for a fixed target amount
/// @param _origin the address of the origin
/// @param _target the address of the target
/// @param _originAmount the origin amount
/// @param _minTargetAmount the minimum target amount
/// @param _deadline deadline in block number after which the trade will not execute
/// @return targetAmount_ the amount of target that has been swapped for the origin amount
|
function originSwap (
address _origin,
address _target,
uint _originAmount,
uint _minTargetAmount,
uint _deadline
) external deadline(_deadline) transactable nonReentrant returns (
uint targetAmount_
) {
targetAmount_ = Swaps.originSwap(component, _origin, _target, _originAmount, msg.sender);
require(targetAmount_ > _minTargetAmount, "Component/below-min-target-amount");
}
|
0.5.17
|
/// @notice PolygonCommunityVault initializer
/// @dev Needs to be called after deployment. Get addresses from https://github.com/maticnetwork/static/tree/master/network
/// @param _token The address of the ERC20 that the vault will manipulate/own
/// @param _rootChainManager Polygon root network chain manager. Zero address for child deployment
/// @param _erc20Predicate Polygon ERC20 Predicate. Zero address for child deployment
|
function initialize(address _token, address _rootChainManager, address _erc20Predicate) public initializer {
require(_token != address(0), "Vault: a valid token address must be provided");
__Ownable_init();
token = _token;
if (_rootChainManager != address(0)) {
require(_erc20Predicate != address(0), "Vault: erc20Predicate must not be 0x0");
erc20Predicate = _erc20Predicate;
rootChainManager = IRootChainManager(_rootChainManager);
}
}
|
0.8.6
|
/// @author james foley http://github.com/realisation
/// @notice selectively deposit any supported stablecoin flavor into the contract in return for corresponding amount of component tokens
/// @param _derivatives an array containing the addresses of the flavors being deposited into
/// @param _amounts an array containing the values of the flavors you wish to deposit into the contract. each amount should have the same index as the flavor it is meant to deposit
/// @param _minComponents minimum acceptable amount of components
/// @param _deadline deadline for tx
/// @return componentsToMint_ the amount of components to mint for the deposited stablecoin flavors
|
function selectiveDeposit (
address[] calldata _derivatives,
uint[] calldata _amounts,
uint _minComponents,
uint _deadline
) external deadline(_deadline) transactable nonReentrant returns (
uint componentsMinted_
) {
componentsMinted_ = SelectiveLiquidity.selectiveDeposit(component, _derivatives, _amounts, _minComponents);
}
|
0.5.17
|
/// @author james foley http://github.com/realisation
/// @notice selectively withdrawal any supported stablecoin flavor from the contract by burning a corresponding amount of component tokens
/// @param _derivatives an array of flavors to withdraw from the reserves
/// @param _amounts an array of amounts to withdraw that maps to _flavors
/// @param _maxComponents the maximum amount of components you want to burn
/// @param _deadline timestamp after which the transaction is no longer valid
/// @return componentsBurned_ the corresponding amount of component tokens to withdraw the specified amount of specified flavors
|
function selectiveWithdraw (
address[] calldata _derivatives,
uint[] calldata _amounts,
uint _maxComponents,
uint _deadline
) external deadline(_deadline) transactable nonReentrant returns (
uint componentsBurned_
) {
componentsBurned_ = SelectiveLiquidity.selectiveWithdraw(component, _derivatives, _amounts, _maxComponents);
}
|
0.5.17
|
/// @notice Transfers full balance of managed token through the Polygon Bridge
/// @dev Emits TransferToChild on funds being sucessfuly deposited
|
function transferToChild() public { // onlyOnRoot , maybe onlyOwner
require(erc20Predicate != address(0), "Vault: transfer to child chain is disabled");
IERC20 erc20 = IERC20(token);
uint256 amount = erc20.balanceOf(address(this));
erc20.approve(erc20Predicate, amount);
rootChainManager.depositFor(address(this), token, abi.encode(amount));
emit TransferToChild(msg.sender, token, amount);
}
|
0.8.6
|
// Constructor
// @notice RAOToken Contract
// @return the transaction address
|
function RAOToken(address _multisig) public {
require(_multisig != 0x0);
multisig = _multisig;
RATE = initialPrice;
startTime = now;
// the balances will be sealed for 6 months
sealdate = startTime + 180 days;
// for now the token sale will run for 30 days
endTime = startTime + 60 days;
balances[multisig] = _totalSupply;
owner = msg.sender;
}
|
0.4.19
|
/**
* @dev Add time lock, only locker can add
*/
|
function _addTimeLock(
address account,
uint256 amount,
uint256 expiresAt
) internal {
require(amount > 0, "Time Lock: lock amount must be greater than 0");
require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now");
_timeLocks[account].push(TimeLock(amount, expiresAt));
emit TimeLocked(account);
}
|
0.8.4
|
/**
* @dev Remove time lock, only locker can remove
* @param account The address want to remove time lock
* @param index Time lock index
*/
|
function _removeTimeLock(address account, uint8 index) internal {
require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid");
uint256 len = _timeLocks[account].length;
if (len - 1 != index) {
// if it is not last item, swap it
_timeLocks[account][index] = _timeLocks[account][len - 1];
}
_timeLocks[account].pop();
emit TimeUnlocked(account);
}
|
0.8.4
|
/**
* @dev get total time locked amount of address
* @param account The address want to know the time lock amount.
* @return time locked amount
*/
|
function getTimeLockedAmount(address account) public view returns (uint256) {
uint256 timeLockedAmount = 0;
uint256 len = _timeLocks[account].length;
for (uint256 i = 0; i < len; i++) {
if (block.timestamp < _timeLocks[account][i].expiresAt) {
timeLockedAmount = timeLockedAmount + _timeLocks[account][i].amount;
}
}
return timeLockedAmount;
}
|
0.8.4
|
/**
* @dev Add investor lock, only locker can add
* @param account investor lock account.
* @param amount investor lock amount.
* @param startsAt investor lock release start date.
* @param period investor lock period.
* @param count investor lock count. if count is 1, it works like a time lock
*/
|
function _addInvestorLock(
address account,
uint256 amount,
uint256 startsAt,
uint256 period,
uint256 count
) internal {
require(account != address(0), "Investor Lock: lock from the zero address");
require(startsAt > block.timestamp, "Investor Lock: must set after now");
require(amount > 0, "Investor Lock: amount is 0");
require(period > 0, "Investor Lock: period is 0");
require(count > 0, "Investor Lock: count is 0");
_investorLocks[account] = InvestorLock(amount, startsAt, period, count);
emit InvestorLocked(account);
}
|
0.8.4
|
/**
* @dev get total investor locked amount of address, locked amount will be released by 100%/months
* if months is 5, locked amount released 20% per 1 month.
* @param account The address want to know the investor lock amount.
* @return investor locked amount
*/
|
function getInvestorLockedAmount(address account) public view returns (uint256) {
uint256 investorLockedAmount = 0;
uint256 amount = _investorLocks[account].amount;
if (amount > 0) {
uint256 startsAt = _investorLocks[account].startsAt;
uint256 period = _investorLocks[account].period;
uint256 count = _investorLocks[account].count;
uint256 expiresAt = startsAt + period * (count - 1);
uint256 timestamp = block.timestamp;
if (timestamp < startsAt) {
investorLockedAmount = amount;
} else if (timestamp < expiresAt) {
investorLockedAmount = (amount * ((expiresAt - timestamp) / period + 1)) / count;
}
}
return investorLockedAmount;
}
|
0.8.4
|
/**
* @dev lock and pause before transfer token
*/
|
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal override(ERC20) {
super._beforeTokenTransfer(from, to, amount);
require(!isLocked(from), "Lockable: token transfer from locked account");
require(!isLocked(to), "Lockable: token transfer to locked account");
require(!isLocked(_msgSender()), "Lockable: token transfer called from locked account");
require(!paused(), "Pausable: token transfer while paused");
require(balanceOf(from) - getTimeLockedAmount(from) - getInvestorLockedAmount(from) >= amount, "Lockable: token transfer from time locked account");
}
|
0.8.4
|
/**
* @dev Function to mint tokens
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
|
function mintOwner(uint256 value) public onlyMinter returns (bool) {
require(msg.sender != address(0), "");
require(msg.sender == _owner, "");
_totalSupply = safeAdd(_totalSupply, value);
balances[_owner] = safeAdd(balances[_owner], value);
emit Transfer(address(0), _owner, value);
return true;
}
|
0.5.0
|
// Deposit ERC20's for saving
|
function depositToken(uint256 amount) public {
require(isEnded != true, "Deposit ended");
require(lockStartTime < now, 'Event has not been started yet');
require(isAddrWhitelisted[msg.sender] == true, "Address is not whitelisted.");
require(Add(currentCap, amount) <= HARD_CAP, 'Exceed limit total cap');
require(Token(KAI_ADDRESS).transferFrom(msg.sender, address(this), amount));
currentCap = Add(currentCap, amount);
addrBalance[msg.sender] = Add(addrBalance[msg.sender], amount);
}
|
0.5.0
|
// Withdraw ERC20's to personal address
|
function withdrawToken() public {
require(lockStartTime + lockDays * 1 days < now, "Locking period");
uint256 amount = addrBalance[msg.sender];
require(amount > 0, "withdraw only once");
uint256 _interest = Mul(amount, interest) / 10000;
bonus = Sub(bonus, _interest);
amount = Add(amount, _interest);
require(Token(KAI_ADDRESS).transfer(msg.sender, amount));
addrBalance[msg.sender] = 0;
}
|
0.5.0
|
/**
* Initialization Construction
*/
|
function TokenERC20(uint256 _initialSupply, string _tokenName, string _tokenSymbol) public {
totalSupply = _initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = _tokenName; // Set the name for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
|
0.4.16
|
/**
* Internal Realization of Token Transaction Transfer
*/
|
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(balanceOf[_from] >= _value); // Check if the sender has enough
require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Save this for an assertion in the future
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value); // Notify anyone listening that this transfer took place
assert(balanceOf[_from] + balanceOf[_to] == previousBalances); // Use assert to check code logic
}
|
0.4.16
|
/**
* @dev convert bytes to address
*/
|
function bytesToAddress(bytes source) internal returns(address) {
uint result;
uint mul = 1;
for(uint i = 20; i > 0; i--) {
result += uint8(source[i-1])*mul;
mul = mul*256;
}
return address(result);
}
|
0.4.18
|
// gas estimation: 105340
|
function give (string name, uint maxValuePerOpen, string giver) payable {
RedEnvelope storage e = envelopes[name];
require(e.value == 0);
require(msg.value > 0);
e.balance = e.value = msg.value;
e.maxValuePerOpen = maxValuePerOpen;
e.giver = giver;
}
|
0.4.19
|
// verify that the sender address does belong to a forum user
|
function _authenticate (string forumId, uint cbGasLimit) payable {
require(stringToUint(forumId) < maxAllowedId);
require(forumIdToAddr[forumId] == 0);
require(msg.value >= oraclize_getPrice("URL", cbGasLimit));
// looks like the page is too broken for oralize's xpath handler
// bytes32 queryId = oraclize_query("URL", 'html(http://8btc.com/home.php?mod=space&do=doing&uid=250950).xpath(//*[@id="ct"]//div[@class="xld xlda"]/dl[1]/dd[2]/span/text())');
bytes32 queryId = oraclize_query("URL",
/*
"json(http://redproxy-1.appspot.com/getAddress.php).addr",
concat("x", forumId) // buggy oraclize
*/
concat("json(http://redproxy-1.appspot.com/getAddress.php?uid=", forumId, ").addr"),
cbGasLimit
);
pendingQueries[queryId] = forumId;
}
|
0.4.19
|
// for now we don't use real randomness
// gas estimation: 57813 x 4 gwei = 0.0002356 eth * 1132 usd/eth = 0.27 usd
|
function open (string envelopeName) returns (uint value) {
string forumId = addrToForumId[msg.sender];
require(bytes(forumId).length > 0);
RedEnvelope e = envelopes[envelopeName];
require(e.balance > 0);
require(e.takers[msg.sender] == 0);
value = uint(keccak256(envelopeName, msg.sender)) % e.maxValuePerOpen;
if (value > e.balance) {
value = e.balance;
}
e.balance -= value;
e.takers[msg.sender] = value;
msg.sender.transfer(value);
}
|
0.4.19
|
/// @dev user's staked information
|
function getUserStaked(address user)
external
view
returns (
uint256 amount,
uint256 claimedBlock,
uint256 claimedAmount,
uint256 releasedBlock,
uint256 releasedAmount,
uint256 releasedTOSAmount,
bool released
)
{
return (
userStaked[user].amount,
userStaked[user].claimedBlock,
userStaked[user].claimedAmount,
userStaked[user].releasedBlock,
userStaked[user].releasedAmount,
userStaked[user].releasedTOSAmount,
userStaked[user].released
);
}
|
0.7.6
|
// function to mint based off of whitelist allocation
|
function presaleMint(
uint256 amount,
bytes32 leaf,
bytes32[] memory proof
) external payable {
require(presaleActive, "Presale not active");
// create storage element tracking user mints if this is the first mint for them
if (!whitelistUsed[msg.sender]) {
// verify that msg.sender corresponds to Merkle leaf
require(keccak256(abi.encodePacked(msg.sender)) == leaf, "Sender doesn't match Merkle leaf");
// verify that (leaf, proof) matches the Merkle root
require(verify(merkleRoot, leaf, proof), "Not a valid leaf in the Merkle tree");
whitelistUsed[msg.sender] = true;
}
require(amount <= MAX_AMOUNT_PER_MINT, "Minting too many at a time");
require(msg.value == amount * presaleMintPrice, "Not enough ETH sent");
require(amount + totalSupply() <= currentSupplyCap, "Would exceed max supply");
_safeMint(msg.sender, amount);
emit Mint(msg.sender, amount);
}
|
0.8.12
|
// function to mint in public sale
|
function publicMint(uint256 amount) external payable {
require(saleActive, "Public sale not active");
require(amount <= MAX_AMOUNT_PER_MINT, "Minting too many at a time");
require(msg.value == amount * publicMintPrice, "Not enough ETH sent");
require(amount + totalSupply() <= currentSupplyCap, "Would exceed max supply");
// _safeMint(msg.sender, amount);
_mint(msg.sender, amount, "", false);
emit Mint(msg.sender, amount);
}
|
0.8.12
|
// how many tokens sold through crowdsale
//@dev fallback function, only accepts ether if ICO is running or Reject
|
function () payable public {
require(icoEndDate > now);
require(icoStartDate < now);
require(!safeguard);
uint ethervalueWEI=msg.value;
// calculate token amount to be sent
uint256 token = ethervalueWEI.mul(exchangeRate); //weiamount * price
tokensSold = tokensSold.add(token);
_transfer(this, msg.sender, token); // makes the transfers
forwardEherToOwner();
}
|
0.4.25
|
/**
* Internal transfer, only can be called by this contract
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
|
function _transfer(address _from, address _to, uint _value) internal {
// Check if the address is empty
require(_to != address(0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
|
0.5.10
|
/// @notice Causes the deposit of amount sender tokens.
/// @param _amount Amount of the tokens.
|
function deposit(uint256 _amount) whenNotPaused nonReentrant public override {
uint256 _pool = balance();
uint256 _before = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransferFrom(_msgSender(), address(this), _amount);
uint256 _after = IERC20(token).balanceOf(address(this));
_amount = _after.sub(_before); // Additional check for deflationary tokens
uint256 shares = 0;
if (totalSupply() == 0) {
shares = _amount;
} else {
shares = (_amount.mul(totalSupply())).div(_pool);
}
_mint(_msgSender(), shares);
}
|
0.6.12
|
/// @notice Causes the withdraw of amount sender shares.
/// @param _shares Amount of the shares.
|
function withdraw(uint256 _shares) whenNotPaused public override {
uint256 r = (balance().mul(_shares)).div(totalSupply());
_burn(_msgSender(), _shares);
// Check balance
uint256 b = IERC20(token).balanceOf(address(this));
if (b < r) {
uint256 _withdraw = r.sub(b);
IController(controller).withdraw(_withdraw);
uint256 _after = IERC20(token).balanceOf(address(this));
require(_after >= r, "Not enough balance");
}
IERC20(token).safeTransfer(_msgSender(), r);
}
|
0.6.12
|
/// @notice Set implementation contract
/// @param impl New implementation contract address
|
function upgradeTo(address impl) external onlyOwner {
require(impl != address(0), "StakeTONProxy: input is zero");
require(
_implementation() != impl,
"StakeTONProxy: The input address is same as the state"
);
_setImplementation(impl);
emit Upgraded(impl);
}
|
0.7.6
|
/// @dev fallback function , execute on undefined function call
|
function _fallback() internal {
address _impl = _implementation();
require(
_impl != address(0) && !pauseProxy,
"StakeTONProxy: impl is zero OR proxy is false"
);
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), _impl, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
|
0.7.6
|
/// @dev Approves function
/// @dev call by WTON
/// @param owner who actually calls
/// @param spender Who gives permission to use
/// @param tonAmount how much will be available
/// @param data Amount data to use with users
|
function onApprove(
address owner,
address spender,
uint256 tonAmount,
bytes calldata data
) external override returns (bool) {
(address _spender, uint256 _amount) = _decodeStakeData(data);
require(
tonAmount == _amount && spender == _spender,
"StakeTONProxy: tonAmount != stakingAmount "
);
require(
stakeOnApprove(msg.sender, owner, _spender, _amount),
"StakeTONProxy: stakeOnApprove fails "
);
return true;
}
|
0.7.6
|
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
|
function approve(address spender, uint tokens) public returns (bool success) {
if(tokens > 0 && spender != address(0)) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
} else { return false; }
}
|
0.4.23
|
/// @dev stake with WTON
/// @param from WTON
/// @param _owner who actually calls
/// @param _spender Who gives permission to use
/// @param _amount how much will be available
|
function stakeOnApprove(
address from,
address _owner,
address _spender,
uint256 _amount
) public returns (bool) {
require(
(paytoken == from && _amount > 0 && _spender == address(this)),
"StakeTONProxy: stakeOnApprove init fail"
);
require(
block.number >= saleStartBlock && block.number < startBlock,
"StakeTONProxy: period not allowed"
);
require(
!IStakeVaultStorage(vault).saleClosed(),
"StakeTONProxy: end sale"
);
require(
IIERC20(paytoken).balanceOf(_owner) >= _amount,
"StakeTONProxy: insuffient"
);
LibTokenStake1.StakedAmount storage staked = userStaked[_owner];
if (staked.amount == 0) totalStakers = totalStakers.add(1);
staked.amount = staked.amount.add(_amount);
totalStakedAmount = totalStakedAmount.add(_amount);
require(
IIERC20(from).transferFrom(_owner, _spender, _amount),
"StakeTONProxy: transfer fail"
);
emit Staked(_owner, _amount);
return true;
}
|
0.7.6
|
/// @dev set initial storage
/// @param _addr the array addresses of token, paytoken, vault, defiAddress
/// @param _registry the registry address
/// @param _intdata the array valued of saleStartBlock, stakeStartBlock, periodBlocks
|
function setInit(
address[4] memory _addr,
address _registry,
uint256[3] memory _intdata
) external onlyOwner {
require(token == address(0), "StakeTONProxy: already initialized");
require(
_registry != address(0) &&
_addr[2] != address(0) &&
_intdata[0] < _intdata[1],
"StakeTONProxy: setInit fail"
);
token = _addr[0];
paytoken = _addr[1];
vault = _addr[2];
defiAddr = _addr[3];
stakeRegistry = _registry;
tokamakLayer2 = address(0);
saleStartBlock = _intdata[0];
startBlock = _intdata[1];
endBlock = startBlock.add(_intdata[2]);
}
|
0.7.6
|
/**
* @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and
* whether or not `from` has a balance of at least `amount`. Does NOT do a transfer.
*/
|
function checkTransferIn(address asset, address from, uint amount) internal view returns (Error) {
EIP20Interface token = EIP20Interface(asset);
if (token.allowance(from, address(this)) < amount) {
return Error.TOKEN_INSUFFICIENT_ALLOWANCE;
}
if (token.balanceOf(from) < amount) {
return Error.TOKEN_INSUFFICIENT_BALANCE;
}
return Error.NO_ERROR;
}
|
0.4.26
|
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory
* error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to
* insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call,
* and it returned Error.NO_ERROR, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
|
function doTransferIn(address asset, address from, uint amount) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);
bool result;
token.transferFrom(from, address(this), amount);
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Error.TOKEN_TRANSFER_FAILED;
}
return Error.NO_ERROR;
}
|
0.4.26
|
/**
* @dev Calculates a new balance based on a previous balance and a pair of interest indices
* This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex
* value and divided by the user's checkpoint index value`
*
* TODO: Is there a way to handle this that is less likely to overflow?
*/
|
function calculateBalance(uint startingBalance, uint interestIndexStart, uint interestIndexEnd) pure internal returns (Error, uint) {
if (startingBalance == 0) {
// We are accumulating interest on any previous balance; if there's no previous balance, then there is
// nothing to accumulate.
return (Error.NO_ERROR, 0);
}
(Error err0, uint balanceTimesIndex) = mul(startingBalance, interestIndexEnd);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return div(balanceTimesIndex, interestIndexStart);
}
|
0.4.26
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.