comment
stringlengths 11
2.99k
| function_code
stringlengths 165
3.15k
| version
stringclasses 80
values |
---|---|---|
//lets leave
//if we can't deleverage in one go set collateralFactor to 0 and call harvest multiple times until delevered
|
function prepareMigration(address _newStrategy) internal override {
if(!forceMigrate){
(uint256 deposits, uint256 borrows) = getLivePosition();
_withdrawSome(deposits.sub(borrows));
(, , uint256 borrowBalance, ) = cToken.getAccountSnapshot(address(this));
require(borrowBalance < 10_000);
IERC20 _comp = IERC20(comp);
uint _compB = _comp.balanceOf(address(this));
if(_compB > 0){
_comp.safeTransfer(_newStrategy, _compB);
}
}
}
|
0.6.12
|
//Three functions covering normal leverage and deleverage situations
// max is the max amount we want to increase our borrowed balance
// returns the amount we actually did
|
function _noFlashLoan(uint256 max, bool deficit) internal returns (uint256 amount) {
//we can use non-state changing because this function is always called after _calculateDesiredPosition
(uint256 lent, uint256 borrowed) = getCurrentPosition();
//if we have nothing borrowed then we can't deleverage any more
if (borrowed == 0 && deficit) {
return 0;
}
(, uint256 collateralFactorMantissa, ) = compound.markets(address(cToken));
if (deficit) {
amount = _normalDeleverage(max, lent, borrowed, collateralFactorMantissa);
} else {
amount = _normalLeverage(max, lent, borrowed, collateralFactorMantissa);
}
emit Leverage(max, amount, deficit, address(0));
}
|
0.6.12
|
//maxDeleverage is how much we want to reduce by
|
function _normalDeleverage(
uint256 maxDeleverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 deleveragedAmount) {
uint256 theoreticalLent = 0;
//collat ration should never be 0. if it is something is very wrong... but just incase
if(collatRatio != 0){
theoreticalLent = borrowed.mul(1e18).div(collatRatio);
}
deleveragedAmount = lent.sub(theoreticalLent);
if (deleveragedAmount >= borrowed) {
deleveragedAmount = borrowed;
}
if (deleveragedAmount >= maxDeleverage) {
deleveragedAmount = maxDeleverage;
}
uint256 exchangeRateStored = cToken.exchangeRateStored();
//redeemTokens = redeemAmountIn *1e18 / exchangeRate. must be more than 0
//a rounding error means we need another small addition
if(deleveragedAmount.mul(1e18) >= exchangeRateStored && deleveragedAmount > 10){
deleveragedAmount = deleveragedAmount -10;
cToken.redeemUnderlying(deleveragedAmount);
//our borrow has been increased by no more than maxDeleverage
cToken.repayBorrow(deleveragedAmount);
}
}
|
0.6.12
|
//maxDeleverage is how much we want to increase by
|
function _normalLeverage(
uint256 maxLeverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 leveragedAmount) {
uint256 theoreticalBorrow = lent.mul(collatRatio).div(1e18);
leveragedAmount = theoreticalBorrow.sub(borrowed);
if (leveragedAmount >= maxLeverage) {
leveragedAmount = maxLeverage;
}
if(leveragedAmount > 10){
leveragedAmount = leveragedAmount -10;
cToken.borrow(leveragedAmount);
cToken.mint(want.balanceOf(address(this)));
}
}
|
0.6.12
|
//DyDx calls this function after doing flash loan
|
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) public override {
(bool deficit, uint256 amount) = abi.decode(data, (bool, uint256));
require(msg.sender == SOLO);
require(sender == address(this));
FlashLoanLib.loanLogic(deficit, amount, cToken);
}
|
0.6.12
|
// UPDATE CONTRACT
|
function setInternalDependencies(address[] _newDependencies) public onlyOwner {
super.setInternalDependencies(_newDependencies);
core = Core(_newDependencies[0]);
dragonParams = DragonParams(_newDependencies[1]);
dragonGetter = DragonGetter(_newDependencies[2]);
dragonMarketplace = DragonMarketplace(_newDependencies[3]);
breedingMarketplace = BreedingMarketplace(_newDependencies[4]);
eggMarketplace = EggMarketplace(_newDependencies[5]);
skillMarketplace = SkillMarketplace(_newDependencies[6]);
distribution = Distribution(_newDependencies[7]);
treasury = Treasury(_newDependencies[8]);
gladiatorBattle = GladiatorBattle(_newDependencies[9]);
gladiatorBattleStorage = GladiatorBattleStorage(_newDependencies[10]);
}
|
0.4.25
|
/**
* @dev Binds an iNFT instance to already deployed AI Pod instance
*
* @param _pod address of the deployed AI Pod instance to bind iNFT to
*/
|
function setPodContract(address _pod) public {
// verify sender has permission to access this function
require(isSenderInRole(ROLE_DEPLOYER), "access denied");
// verify the input is set
require(_pod != address(0), "AI Pod addr is not set");
// verify _pod is valid ERC721
require(IERC165(_pod).supportsInterface(type(IERC721).interfaceId), "AI Pod addr is not ERC721");
// setup smart contract internal state
podContract = _pod;
// emit an event
emit PodContractSet(_msgSender(), _pod);
}
|
0.8.4
|
/**
* @dev Binds an iNFT instance to already deployed ALI Token instance
*
* @param _ali address of the deployed ALI Token instance to bind iNFT to
*/
|
function setAliContract(address _ali) public {
// verify sender has permission to access this function
require(isSenderInRole(ROLE_DEPLOYER), "access denied");
// verify the input is set
require(_ali != address(0), "ALI Token addr is not set");
// verify _ali is valid ERC20
require(IERC165(_ali).supportsInterface(type(IERC20).interfaceId), "ALI Token addr is not ERC20");
// setup smart contract internal state
aliContract = _ali;
// emit an event
emit AliContractSet(_msgSender(), _ali);
}
|
0.8.4
|
/**
* @notice Returns an owner of the given iNFT.
* By definition iNFT owner is an owner of the target NFT
*
* @param recordId iNFT ID to query ownership information for
* @return address of the given iNFT owner
*/
|
function ownerOf(uint256 recordId) public view override returns (address) {
// read the token binding
IntelliBinding memory binding = bindings[recordId];
// verify the binding exists and throw standard Zeppelin message if not
require(binding.targetContract != address(0), "iNFT doesn't exist");
// delegate `ownerOf` call to the target NFT smart contract
return IERC721(binding.targetContract).ownerOf(binding.targetId);
}
|
0.8.4
|
// send tokens and ETH for liquidity to contract directly, then call this function.
//(not required, can still use Uniswap to add liquidity manually, but this ensures everything is excluded properly and makes for a great stealth launch)
|
function launch(/*address[] memory airdropWallets, uint256[] memory amounts*/) external onlyOwner returns (bool){
require(!tradingActive, "Trading is already active, cannot relaunch.");
/*require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input.
for(uint256 i = 0; i < airdropWallets.length; i++){
address wallet = airdropWallets[i];
uint256 amount = amounts[i];
_transfer(msg.sender, wallet, amount);
}*/
enableTrading();
/*
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Uniswap Router v2
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
_approve(address(this), address(uniswapV2Router), _tTotal);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
*/
require(address(this).balance > 0, "Must have ETH on contract to launch");
addLiquidity(balanceOf(address(this)), address(this).balance);
//setLiquidityAddress(address(0xdead));
return true;
}
|
0.8.9
|
/*function setGasPriceLimit(uint256 gas) external onlyOwner {
require(gas >= 200);
gasPriceLimit = gas * 1 gwei;
}*/
|
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
external
view
returns (uint256)
{
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
|
0.8.9
|
//withdrawal or refund for investor and beneficiary
|
function safeWithdrawal() public afterDeadline {
if (weiRaised < fundingGoal && weiRaised < minimumFundingGoal) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
FundTransfer(msg.sender, amount, false);
/*tokenReward.burnFrom(msg.sender, price * amount);*/
} else {
balanceOf[msg.sender] = amount;
}
}
}
if ((weiRaised >= fundingGoal || weiRaised >= minimumFundingGoal) && wallet == msg.sender) {
if (wallet.send(weiRaised)) {
FundTransfer(wallet, weiRaised, false);
GoalReached(wallet, weiRaised);
} else {
//If we fail to send the funds to beneficiary, unlock funders balance
fundingGoalReached = false;
}
}
}
|
0.4.18
|
/**
* Fuck the transfer fee
* Who needs it
*/
|
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
|
0.5.15
|
//This is where all your gas goes apparently
|
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.15
|
/**
* @dev Transfer tokens and bonus tokens to a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _bonus The bonus amount.
*/
|
function transferWithBonuses(address _to, uint256 _value, uint256 _bonus) onlyOwner returns (bool) {
require(_to != address(0));
require(balances[msg.sender] - bonuses[msg.sender] * freezingPercentage / 100 >= _value + _bonus);
bonuses[_to] = bonuses[_to].add(_bonus);
return super.transfer(_to, _value + _bonus);
}
|
0.4.24
|
/**
* @dev Buying ethereum for tokens
* @param amount Number of tokens
*/
|
function sell(uint256 amount) external returns (uint256 revenue){
require(balances[msg.sender] - bonuses[msg.sender] * freezingPercentage / 100 >= amount); // Checks if the sender has enough to sell
balances[this] = balances[this].add(amount); // Adds the amount to owner's balance
balances[msg.sender] = balances[msg.sender].sub(amount); // Subtracts the amount from seller's balance
revenue = amount.mul(sellPrice); // Calculate the seller reward
msg.sender.transfer(revenue); // Sends ether to the seller: it's important to do this last to prevent recursion attacks
Transfer(msg.sender, this, amount); // Executes an event reflecting on the change
return revenue; // Ends function and returns
}
|
0.4.24
|
/** @dev number of complete cycles d/m/w/y */
|
function countPeriod(address _investor, bytes5 _t) internal view returns (uint256) {
uint256 _period;
uint256 _now = now; // blocking timestamp
if (_t == _td) _period = 1 * _day;
if (_t == _tw) _period = 7 * _day;
if (_t == _tm) _period = 31 * _day;
if (_t == _ty) _period = 365 * _day;
invest storage inv = investInfo[_investor][_t];
if (_now - inv.created < _period) return 0;
return (_now - inv.created)/_period; // get full days
}
|
0.4.21
|
/** @dev loop 'for' wrapper, where 100,000%, 10^3 decimal */
|
function loopFor(uint256 _condition, uint256 _data, uint256 _bonus) internal pure returns (uint256 r) {
assembly {
for { let i := 0 } lt(i, _condition) { i := add(i, 1) } {
let m := mul(_data, _bonus)
let d := div(m, 100000)
_data := add(_data, d)
}
r := _data
}
}
|
0.4.21
|
/** @dev invest box controller */
|
function rewardController(address _investor, bytes5 _type) internal view returns (uint256) {
uint256 _period;
uint256 _balance;
uint256 _created;
invest storage inv = investInfo[msg.sender][_type];
_period = countPeriod(_investor, _type);
_balance = inv.balance;
_created = inv.created;
uint256 full_steps;
uint256 last_step;
uint256 _d;
if(_type == _td) _d = 365;
if(_type == _tw) _d = 54;
if(_type == _tm) _d = 12;
if(_type == _ty) _d = 1;
full_steps = _period/_d;
last_step = _period - (full_steps * _d);
for(uint256 i=0; i<full_steps; i++) { // not executed if zero
_balance = compaundIntrest(_d, _type, _balance, _created);
_created += 1 years;
}
if(last_step > 0) _balance = compaundIntrest(last_step, _type, _balance, _created);
return _balance;
}
|
0.4.21
|
/**
@dev Compaund Intrest realization, return balance + Intrest
@param _period - time interval dependent from invest time
*/
|
function compaundIntrest(uint256 _period, bytes5 _type, uint256 _balance, uint256 _created) internal view returns (uint256) {
uint256 full_steps;
uint256 last_step;
uint256 _d = 100; // safe divider
uint256 _bonus = bonusSystem(_type, _created);
if (_period>_d) {
full_steps = _period/_d;
last_step = _period - (full_steps * _d);
for(uint256 i=0; i<full_steps; i++) {
_balance = loopFor(_d, _balance, _bonus);
}
if(last_step > 0) _balance = loopFor(last_step, _balance, _bonus);
} else
if (_period<=_d) {
_balance = loopFor(_period, _balance, _bonus);
}
return _balance;
}
|
0.4.21
|
/** @dev make invest */
|
function makeInvest(uint256 _value, bytes5 _interval) internal isMintable {
require(min_invest <= _value && _value <= max_invest); // min max condition
assert(balances[msg.sender] >= _value && balances[this] + _value > balances[this]);
balances[msg.sender] -= _value;
balances[this] += _value;
invest storage inv = investInfo[msg.sender][_interval];
if (inv.exists == false) { // if invest no exists
inv.balance = _value;
inv.created = now;
inv.closed = 0;
emit Transfer(msg.sender, this, _value);
} else
if (inv.exists == true) {
uint256 rew = rewardController(msg.sender, _interval);
inv.balance = _value + rew;
inv.closed = 0;
emit Transfer(0x0, this, rew); // fix rise total supply
}
inv.exists = true;
emit Invested(msg.sender, _value);
if(totalSupply > maxSupply) stopMint(); // stop invest
}
|
0.4.21
|
/** @dev close invest */
|
function closeInvest(bytes5 _interval) internal {
uint256 _intrest;
address _to = msg.sender;
uint256 _period = countPeriod(_to, _interval);
invest storage inv = investInfo[_to][_interval];
uint256 _value = inv.balance;
if (_period == 0) {
balances[this] -= _value;
balances[_to] += _value;
emit Transfer(this, _to, _value); // tx of begining balance
emit InvestClosed(_to, _value);
} else
if (_period > 0) {
// Destruction init
balances[this] -= _value;
totalSupply -= _value;
emit Transfer(this, 0x0, _value);
emit Destruction(_value);
// Issue init
_intrest = rewardController(_to, _interval);
if(manager[msg.sender]) {
_intrest = mulsm(divsm(_intrest, 100), 105); // addition 5% bonus for manager
}
issue(_to, _intrest); // tx of %
emit InvestClosed(_to, _intrest);
}
inv.exists = false; // invest inv clear
inv.balance = 0;
inv.closed = now;
}
|
0.4.21
|
/**
@dev notify owners about their balances was in promo action.
@param _holders addresses of the owners to be notified ["address_1", "address_2", ..]
*/
|
function airdropper(address [] _holders, uint256 _pay_size) public onlyManager {
if(_pay_size == 0) _pay_size = _paySize; // if empty set default
if(_pay_size < 1 * 1e18) revert(); // limit no less then 1 token
uint256 count = _holders.length;
require(count <= 200);
assert(_pay_size * count <= balanceOf(msg.sender));
for (uint256 i = 0; i < count; i++) {
transfer(_holders [i], _pay_size);
}
}
|
0.4.21
|
// https://etherscan.io/address/0x7bd29408f11d2bfc23c34f18275bbf23bb716bc7#code
|
function randomBotIndex() private returns (uint256) {
uint256 totalSize = N_BOT - numBought();
uint256 index = uint256(
keccak256(
abi.encodePacked(
nonce,
msg.sender,
block.difficulty,
block.timestamp
)
)
) % totalSize;
uint256 value = 0;
if (indices[index] != 0) {
value = indices[index];
} else {
value = index;
}
// Move last value to selected position
if (indices[totalSize - 1] == 0) {
// Array position not initialized, so use position
indices[index] = totalSize - 1;
} else {
// Array position holds a value so use that
indices[index] = indices[totalSize - 1];
}
nonce++;
// Don't allow a zero index, start counting at N_PREMINT + 1
return value + N_PREMINT + 1;
}
|
0.8.9
|
// Get the price in wei with early bird discount.
|
function getPrice() public view returns (uint256) {
uint256 numMinted = numBought();
if (numMinted < 1000) {
return 2 * basePrice;
} else if (numMinted < 2000) {
return 5 * basePrice;
} else if (numMinted < 5000) {
return 8 * basePrice;
} else if (numMinted < 7500) {
return 10 * basePrice;
} else {
return 15 * basePrice;
}
}
|
0.8.9
|
// Batch transfer up to 100 tokenIds. Input must be sorted and deduped.
|
function safeTransferFromBatch(address from, address to, uint256[] memory sortedAndDedupedTokenIds) public nonReentrant {
uint length = sortedAndDedupedTokenIds.length;
require(length <= TRANSFER_BATCH_SIZE, "Exceeded batch size.");
uint lastTokenId = 0;
for (uint i=0; i<length; i++) {
require(i == 0 || (sortedAndDedupedTokenIds[i] > lastTokenId), "Token IDs must be sorted and deduped.");
lastTokenId = sortedAndDedupedTokenIds[i];
safeTransferFrom(from, to, sortedAndDedupedTokenIds[i]);
}
}
|
0.8.9
|
// function to temporarily pause token sale if needed
|
function pauseTokenSale() onlyAdmin public {
// confirm the token sale hasn't already completed
require(tokenSaleHasFinished() == false);
// confirm the token sale isn't already paused
require(tokenSaleIsPaused == false);
// pause the sale and note the time of the pause
tokenSaleIsPaused = true;
tokenSalePausedTime = now;
emit SalePaused("token sale has been paused", now);
}
|
0.4.24
|
// function to resume token sale
|
function resumeTokenSale() onlyAdmin public {
// confirm the token sale is currently paused
require(tokenSaleIsPaused == true);
tokenSaleResumedTime = now;
// now calculate the difference in time between the pause time
// and the resume time, to establish how long the sale was
// paused for. This time now needs to be added to the closingTime.
// Note: if the token sale was paused whilst the sale was live and was
// paused before the sale ended, then the value of tokenSalePausedTime
// will always be less than the value of tokenSaleResumedTime
tokenSalePausedDuration = tokenSaleResumedTime.sub(tokenSalePausedTime);
// add the total pause time to the closing time.
closingTime = closingTime.add(tokenSalePausedDuration);
// extend post ICO countdown for the web-site
postIcoPhaseCountdown = closingTime.add(14 days);
// now resume the token sale
tokenSaleIsPaused = false;
emit SaleResumed("token sale has now resumed", now);
}
|
0.4.24
|
// ----------------------------------------------------------------------------
// function for front-end token purchase on our website ***DO NOT OVERRIDE***
// buyer = Address of the wallet performing the token purchase
// ----------------------------------------------------------------------------
|
function buyTokens(address buyer) public payable {
// check Crowdsale is open (can disable for testing)
require(openingTime <= block.timestamp);
require(block.timestamp < closingTime);
// minimum purchase of 100 tokens (0.1 eth)
require(msg.value >= minSpend);
// maximum purchase per transaction to allow broader
// token distribution during tokensale
require(msg.value <= maxSpend);
// stop sales of tokens if token balance is 0
require(tokenSaleTokenBalance() > 0);
// stop sales of tokens if Token sale is paused
require(tokenSaleIsPaused == false);
// log the amount being sent
uint256 weiAmount = msg.value;
preValidatePurchase(buyer, weiAmount);
// calculate token amount to be sold
uint256 tokens = getTokenAmount(weiAmount);
// check that the amount of eth being sent by the buyer
// does not exceed the equivalent number of tokens remaining
require(tokens <= tokenSaleTokenBalance());
// update state
weiRaised = weiRaised.add(weiAmount);
processPurchase(buyer, tokens);
emit TokenPurchase(
msg.sender,
buyer,
weiAmount,
tokens
);
updatePurchasingState(buyer, weiAmount);
forwardFunds();
postValidatePurchase(buyer, weiAmount);
}
|
0.4.24
|
//Play Function (play by contract function call)
|
function Play(bool flipped) equalGambleValue onlyActive resolvePendingRound{
if ( index_player_in_round%2==0 ) { //first is matcher
matchers.push(Gamble(msg.sender, flipped));
}
else {
contrarians.push(Gamble(msg.sender, flipped));
}
index_player+=1;
index_player_in_round+=1;
times_played_history[msg.sender]+=1;
if (index_player_in_round>=round_min_size && index_player_in_round%2==0) {
bool end = randomEnd();
if (end) {
pendingRound=true;
blockEndRound=block.number;}
}
}
|
0.3.1
|
//Function to end Round and pay winners
|
function endRound() private {
delete results;
uint256 random_start_contrarian = randomGen(index_player,(index_player_in_round)/2)-1;
uint256 payout_total;
for (var k = 0; k < (index_player_in_round)/2; k++) {
uint256 index_contrarian;
if (k+random_start_contrarian<(index_player_in_round)/2){
index_contrarian=k+random_start_contrarian;
}
else{
index_contrarian=(k+random_start_contrarian)-(index_player_in_round/2);
}
uint256 information_cost_matcher = information_cost * k;
uint256 payout_matcher = 2*(gamble_value-information_cost_matcher);
uint256 information_cost_contrarian = information_cost * index_contrarian;
uint256 payout_contrarian = 2*(gamble_value-information_cost_contrarian);
results.push(Result(matchers[k].player,matchers[k].flipped,payout_matcher,contrarians[index_contrarian].player,contrarians[index_contrarian].flipped, payout_contrarian));
if (matchers[k].flipped == contrarians[index_contrarian].flipped) {
matchers[k].player.send(payout_matcher);
payout_total+=payout_matcher;
payout_history[matchers[k].player]+=payout_matcher;
}
else {
contrarians[index_contrarian].player.send(payout_contrarian);
payout_total+=payout_contrarian;
payout_history[contrarians[k].player]+=payout_contrarian;
}
}
index_round_ended+=1;
owner.send(index_player_in_round*gamble_value-payout_total);
payout_total=0;
index_player_in_round=0;
delete matchers;
delete contrarians;
pendingRound=false;
if (terminate_after_round==true) state=State.Deactivated;
}
|
0.3.1
|
//Full Refund of Current Round (if needed)
|
function refundRound()
onlyActive
onlyOwner noEthSent{
uint totalRefund;
uint balanceBeforeRefund=this.balance;
for (var k = 0; k< matchers.length; k++) {
matchers[k].player.send(gamble_value);
totalRefund+=gamble_value;
}
for (var j = 0; j< contrarians.length ; j++) {
contrarians[j].player.send(gamble_value);
totalRefund+=gamble_value;
}
delete matchers;
delete contrarians;
state=State.Deactivated;
index_player_in_round=0;
uint balanceLeft = balanceBeforeRefund-totalRefund;
if (balanceLeft >0) owner.send(balanceLeft);
}
|
0.3.1
|
//Function to change game settings (within limits)
//(to adapt to community feedback, popularity)
|
function config(uint new_max_round, uint new_min_round, uint new_information_cost, uint new_gamble_value)
onlyOwner
onlyInactive noEthSent{
if (new_max_round<new_min_round) throw;
if (new_information_cost > new_gamble_value/100) throw;
round_max_size = new_max_round;
round_min_size = new_min_round;
information_cost= new_information_cost;
gamble_value = new_gamble_value;
}
|
0.3.1
|
//JSON GLOBAL STATS
|
function gameStats() noEthSent constant returns (uint number_of_player_in_round, uint total_number_of_player, uint number_of_round_ended, bool pending_round_to_resolve, uint block_end_last_round, uint block_last_player, State state, bool pause_contract_after_round)
{
number_of_player_in_round = index_player_in_round;
total_number_of_player = index_player;
number_of_round_ended = index_round_ended;
pending_round_to_resolve = pendingRound;
block_end_last_round = blockEndRound;
block_last_player = blockLastPlayer;
state = state;
pause_contract_after_round = terminate_after_round;
}
|
0.3.1
|
//JSON LAST ROUND RESULT
|
function getLastRoundResults_by_index(uint _index) noEthSent constant returns (address _address_matcher, address _address_contrarian, bool _flipped_matcher, bool _flipped_contrarian, uint _payout_matcher, uint _payout_contrarian) {
_address_matcher=results[_index].player_matcher;
_address_contrarian=results[_index].player_contrarian;
_flipped_matcher = results[_index].flipped_matcher;
_flipped_contrarian = results[_index].flipped_contrarian;
_payout_matcher = results[_index].payout_matcher;
_payout_contrarian = results[_index].payout_contrarian;
}
|
0.3.1
|
//Receive eth and issue tokens at a given rate per token.
//Contest ends at finishTime and will not except eth after that date.
|
function buyTokens() public nonReentrant payable atState(ContestStates.IN_PROGRESS) {
require(msg.value > 0, "Cannot buy tokens with zero ETH");
require(token.isMinter(address(this)), "Contest contract MUST became a minter of token before token sale");
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.div(rate);
weiRaised = weiRaised.add(weiAmount);
token.mint(msg.sender, tokens);
}
|
0.5.12
|
/**
* @dev After burning hook, it will be called during withdrawal process.
* It will withdraw collateral from strategy and transfer it to user.
*/
|
function _afterBurning(uint256 _amount) internal override {
uint256 balanceHere = tokensHere();
if (balanceHere < _amount) {
_withdrawCollateral(_amount.sub(balanceHere));
balanceHere = tokensHere();
_amount = balanceHere < _amount ? balanceHere : _amount;
}
token.safeTransfer(_msgSender(), _amount);
}
|
0.6.12
|
// eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167
|
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
|
0.8.1
|
/// @notice Set a new staking pool address and migrate funds there
/// @param _pools The new pool address
/// @param _poolId The new pool id
|
function migrateSource(address _pools, uint _poolId) external onlyOwner {
// Withdraw ALCX
bumpExchangeRate();
uint poolBalance = pools.getStakeTotalDeposited(address(this), poolId);
pools.withdraw(poolId, poolBalance);
// Update staking pool address and id
pools = IALCXSource(_pools);
poolId = _poolId;
// Deposit ALCX
uint balance = alcx.balanceOf(address(this));
reApprove();
pools.deposit(poolId, balance);
}
|
0.8.11
|
/// @notice Claim and autocompound rewards
|
function bumpExchangeRate() public {
// Claim from pool
pools.claim(poolId);
// Bump exchange rate
uint balance = alcx.balanceOf(address(this));
if (balance > 0) {
exchangeRate += (balance * exchangeRatePrecision) / totalSupply;
emit ExchangeRateChange(exchangeRate);
// Restake
pools.deposit(poolId, balance);
}
}
|
0.8.11
|
/// @notice Deposit new funds into the staking pool
/// @param amount The amount of ALCX to deposit
|
function stake(uint amount) external {
// Get current exchange rate between ALCX and gALCX
bumpExchangeRate();
// Then receive new deposits
bool success = alcx.transferFrom(msg.sender, address(this), amount);
require(success, "Transfer failed");
pools.deposit(poolId, amount);
// gAmount always <= amount
uint gAmount = amount * exchangeRatePrecision / exchangeRate;
_mint(msg.sender, gAmount);
emit Stake(msg.sender, gAmount, amount);
}
|
0.8.11
|
/// @notice Withdraw funds from the staking pool
/// @param gAmount the amount of gALCX to withdraw
|
function unstake(uint gAmount) external {
bumpExchangeRate();
uint amount = gAmount * exchangeRate / exchangeRatePrecision;
_burn(msg.sender, gAmount);
// Withdraw ALCX and send to user
pools.withdraw(poolId, amount);
bool success = alcx.transfer(msg.sender, amount); // Should return true or revert, but doesn't hurt
require(success, "Transfer failed");
emit Unstake(msg.sender, gAmount, amount);
}
|
0.8.11
|
/**
* Update block durations for various types of visits
*/
|
function changeVisitLengths(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner {
visitLength[uint8(VisitType.Spa)] = _spa;
visitLength[uint8(VisitType.Afternoon)] = _afternoon;
visitLength[uint8(VisitType.Day)] = _day;
visitLength[uint8(VisitType.Overnight)] = _overnight;
visitLength[uint8(VisitType.Week)] = _week;
visitLength[uint8(VisitType.Extended)] = _extended;
}
|
0.4.15
|
/**
* Update ether costs for various types of visits
*/
|
function changeVisitCosts(uint _spa, uint _afternoon, uint _day, uint _overnight, uint _week, uint _extended) onlyOwner {
visitCost[uint8(VisitType.Spa)] = _spa;
visitCost[uint8(VisitType.Afternoon)] = _afternoon;
visitCost[uint8(VisitType.Day)] = _day;
visitCost[uint8(VisitType.Overnight)] = _overnight;
visitCost[uint8(VisitType.Week)] = _week;
visitCost[uint8(VisitType.Extended)] = _extended;
}
|
0.4.15
|
//_arr1:tokenGive,tokenGet,maker,taker
//_arr2:amountGive,amountGet,amountGetTrade,expireTime
//_arr3:rMaker,sMaker,rTaker,sTaker
//parameters are from taker's perspective
|
function trade(address[] _arr1, uint256[] _arr2, uint8 _vMaker,uint8 _vTaker, bytes32[] _arr3) public {
require(isLegacy== false&& now <= _arr2[3]);
uint256 _amountTokenGiveTrade= _arr2[0].mul(_arr2[2]).div(_arr2[1]);
require(_arr2[2]<= IBalance(contractBalance).getAvailableBalance(_arr1[1], _arr1[2])&&_amountTokenGiveTrade<= IBalance(contractBalance).getAvailableBalance(_arr1[0], _arr1[3]));
bytes32 _hash = keccak256(abi.encodePacked(this, _arr1[1], _arr1[0], _arr2[1], _arr2[0], _arr2[3]));
require(ecrecover(_hash, _vMaker, _arr3[0], _arr3[1]) == _arr1[2]
&& ecrecover(keccak256(abi.encodePacked(this, _arr1[0], _arr1[1], _arr2[0], _arr2[1], _arr2[2], _arr1[2], _arr2[3])), _vTaker, _arr3[2], _arr3[3]) == _arr1[3]
&& account2Order2TradeAmount[_arr1[2]][_hash].add(_arr2[2])<= _arr2[1]);
uint256 _commission= _arr2[2].mul(commissionRatio).div(10000);
IBalance(contractBalance).modifyBalance(_arr1[3], _arr1[1], _arr2[2].sub(_commission), true);
IBalance(contractBalance).modifyBalance(_arr1[2], _arr1[1], _arr2[2], false);
IBalance(contractBalance).modifyBalance(_arr1[3], _arr1[0], _amountTokenGiveTrade, false);
IBalance(contractBalance).modifyBalance(_arr1[2], _arr1[0], _amountTokenGiveTrade, true);
account2Order2TradeAmount[_arr1[2]][_hash]= account2Order2TradeAmount[_arr1[2]][_hash].add(_arr2[2]);
if(_arr1[1]== address(0)) {
IBalance(contractBalance).distributeEthProfit(_arr1[3], _commission);
}
else {
IBalance(contractBalance).distributeTokenProfit(_arr1[3], _arr1[1], _commission);
}
emit OnTrade(_arr1[0], _arr1[1], _arr1[2], _arr1[3], _arr2[0], _arr2[1], _arr2[2], now);
}
|
0.4.24
|
// NOTE: Only allows 1 active sale per address per sig, unless owner
|
function postSale(address seller, bytes32 sig, uint256 price) internal {
SaleListLib.addSale(_sigToSortedSales[sig], seller, price);
_addressToSigToSalePrice[seller][sig] = price;
sigToNumSales[sig] = sigToNumSales[sig].add(1);
if (seller == owner) {
_ownerSigToNumSales[sig] = _ownerSigToNumSales[sig].add(1);
}
emit SalePosted(seller, sig, price);
}
|
0.4.23
|
// NOTE: Special remove logic for contract owner's sale!
|
function cancelSale(address seller, bytes32 sig) internal {
if (seller == owner) {
_ownerSigToNumSales[sig] = _ownerSigToNumSales[sig].sub(1);
if (_ownerSigToNumSales[sig] == 0) {
SaleListLib.removeSale(_sigToSortedSales[sig], seller);
_addressToSigToSalePrice[seller][sig] = 0;
}
} else {
SaleListLib.removeSale(_sigToSortedSales[sig], seller);
_addressToSigToSalePrice[seller][sig] = 0;
}
sigToNumSales[sig] = sigToNumSales[sig].sub(1);
emit SaleCancelled(seller, sig);
}
|
0.4.23
|
// Used to set initial shareholders
|
function addShareholderAddress(address newShareholder) external onlyOwner {
// Don't let shareholder be address(0)
require(newShareholder != address(0));
// Contract owner can't be a shareholder
require(newShareholder != owner);
// Must be an open shareholder spot!
require(shareholder1 == address(0) || shareholder2 == address(0) || shareholder3 == address(0));
if (shareholder1 == address(0)) {
shareholder1 = newShareholder;
numShareholders = numShareholders.add(1);
} else if (shareholder2 == address(0)) {
shareholder2 = newShareholder;
numShareholders = numShareholders.add(1);
} else if (shareholder3 == address(0)) {
shareholder3 = newShareholder;
numShareholders = numShareholders.add(1);
}
}
|
0.4.23
|
// Splits the amount specified among shareholders equally
|
function payShareholders(uint256 amount) internal {
// If no shareholders, shareholder fees will be held in contract to be withdrawable by owner
if (numShareholders > 0) {
uint256 perShareholderFee = amount.div(numShareholders);
if (shareholder1 != address(0)) {
asyncSend(shareholder1, perShareholderFee);
}
if (shareholder2 != address(0)) {
asyncSend(shareholder2, perShareholderFee);
}
if (shareholder3 != address(0)) {
asyncSend(shareholder3, perShareholderFee);
}
}
}
|
0.4.23
|
// If card is held by contract owner, split among artist + shareholders
|
function paySellerFee(bytes32 sig, address seller, uint256 sellerProfit) private {
if (seller == owner) {
address artist = getArtist(sig);
uint256 artistFee = computeArtistGenesisSaleFee(sig, sellerProfit);
asyncSend(artist, artistFee);
payShareholders(sellerProfit.sub(artistFee));
} else {
asyncSend(seller, sellerProfit);
}
}
|
0.4.23
|
// Handle wallet debit if necessary, pay out fees, pay out seller profit, cancel sale, transfer card
|
function buy(bytes32 sig) external payable {
address seller;
uint256 price;
(seller, price) = getBestSale(sig);
// There must be a valid sale for the card
require(price > 0 && seller != address(0));
// Buyer must have enough Eth via wallet and payment to cover posted price
uint256 availableEth = msg.value.add(payments[msg.sender]);
require(availableEth >= price);
// Debit wallet if msg doesn't have enough value to cover price
if (msg.value < price) {
asyncDebit(msg.sender, price.sub(msg.value));
}
// Split out fees + seller profit
uint256 txFee = computeTxFee(price);
uint256 sellerProfit = price.sub(txFee);
// Pay out seller (special logic for seller == owner)
paySellerFee(sig, seller, sellerProfit);
// Pay out tx fees
payTxFees(sig, txFee);
// Cancel sale
cancelSale(seller, sig);
// Transfer single sig ownership in registry
registryTransfer(seller, msg.sender, sig, 1);
}
|
0.4.23
|
// Can also be used in airdrops, etc.
|
function transferSig(bytes32 sig, uint256 count, address newOwner) external {
uint256 numOwned = getNumSigsOwned(sig);
// Can't transfer cards you don't own
require(numOwned >= count);
// If transferring from contract owner, cancel the proper number of sales if necessary
if (msg.sender == owner) {
uint256 remaining = numOwned.sub(count);
if (remaining < _ownerSigToNumSales[sig]) {
uint256 numSalesToCancel = _ownerSigToNumSales[sig].sub(remaining);
for (uint256 i = 0; i < numSalesToCancel; i++) {
removeSale(sig);
}
}
} else {
// Remove existing sale if transferring all owned cards
if (numOwned == count && _addressToSigToSalePrice[msg.sender][sig] > 0) {
removeSale(sig);
}
}
// Transfer in registry
registryTransfer(msg.sender, newOwner, sig, count);
}
|
0.4.23
|
// function withdrawTokens() public onlyOwner {
// uint256 amount = balanceOf(address(this));
// require(amount > 0, "Not enough tokens available to withdraw");
// _tokenTransfer(address(this),owner(),amount,false);
// }
// function withdrawWETH() public onlyOwner {
// IUniswapV2Pair token = IUniswapV2Pair(uniswapV2Pair);
// uint256 amount = token.balanceOf(address(this));
// require(amount > 0, "Not enough liquidity available to remove and swap that for WETH");
// // approve token transfer to cover all possible scenarios
// token.approve(address(uniswapV2Router), amount);
// // add the liquidity
// uniswapV2Router.removeLiquidity(
// address(this),
// uniswapV2Router.WETH(),
// amount,
// 0, // slippage is unavoidable
// 0, // slippage is unavoidable
// owner(),
// block.timestamp
// );
// }
//this method is responsible for taking all fee, if takeFee is true
|
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
|
0.6.12
|
/**
* @dev Anybody can burn a specific amount of their tokens.
* @param _amount The amount of token to be burned.
*/
|
function burn(uint256 _amount) public {
require(_amount > 0);
require(_amount <= balances[msg.sender]);
// no need to require _amount <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = SafeMath.sub(balances[burner],_amount);
totalSupply = SafeMath.sub(totalSupply,_amount);
emit Transfer(burner, address(0), _amount);
emit Burn(burner, _amount);
}
|
0.4.24
|
/**
* @dev Owner can burn a specific amount of tokens of other token holders.
* @param _from The address of token holder whose tokens to be burned.
* @param _amount The amount of token to be burned.
*/
|
function burnFrom(address _from, uint256 _amount) onlyOwner public {
require(_from != address(0));
require(_amount > 0);
require(_amount <= balances[_from]);
balances[_from] = SafeMath.sub(balances[_from],_amount);
totalSupply = SafeMath.sub(totalSupply,_amount);
emit Transfer(_from, address(0), _amount);
emit Burn(_from, _amount);
}
|
0.4.24
|
/// @dev Accepts ether and creates new tge tokens.
|
function createTokens() payable external {
if (!tokenSaleActive)
revert();
if (haltIco)
revert();
if (msg.value == 0)
revert();
uint256 tokens;
tokens = SafeMath.mul(msg.value, icoTokenExchangeRate); // check that we're not over totals
uint256 checkedSupply = SafeMath.add(totalSupply, tokens);
// return money if something goes wrong
if (tokenCreationCap < checkedSupply)
revert(); // odd fractions won't be found
totalSupply = checkedSupply;
balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here
emit CreateToken(msg.sender, tokens); // logs token creation
}
|
0.4.24
|
//sav3 transfer function
|
function _transfer(address from, address to, uint256 amount) internal {
// calculate liquidity lock amount
// dont transfer burn from this contract
// or can never lock full lockable amount
if(locked && unlocked[from] != true && unlocked[to] != true)
revert("Locked until end of presale");
if (liquidityLockDivisor != 0 && feelessAddr[from] == false && feelessAddr[to] == false) {
uint256 liquidityLockAmount = amount.div(liquidityLockDivisor);
super._transfer(from, address(this), liquidityLockAmount);
super._transfer(from, to, amount.sub(liquidityLockAmount));
}
else {
super._transfer(from, to, amount);
}
}
|
0.5.17
|
// function batchMintAndBurn(uint256[] memory oldID, uint256[] memory newId, bytes32[] memory leaves, bytes32[j][] memory proofs) external {
|
function batchMigration(uint256[] memory oldIds, uint256[] memory newIds, bytes32[] memory leaves, bytes32[][] memory proofs) external returns(address){
for (uint i = 0; i < oldIds.length; i++) {
// Don't allow reminting
require(!_exists(newIds[i]), "Token already minted");
// Verify that (oldId, newId) correspond to the Merkle leaf
require(keccak256(abi.encodePacked(oldIds[i], newIds[i])) == leaves[i], "Ids don't match Merkle leaf");
// Verify that (oldId, newId) is a valid pair in the Merkle tree
//require(verify(merkleRoot, leaves[i], proofs[i]), "Not a valid element in the Merkle tree");
// Verify that msg.sender is the owner of the old token
require(Opensea(openseaSharedAddress).balanceOf(msg.sender, oldIds[i]), "Only token owner can mintAndBurn");
}
for (uint j = 0; j < oldIds.length; j++) {
Opensea(openseaSharedAddress).safeTransferFrom(msg.sender, burnAddress, oldIds[j], 1, "");
_mint(msg.sender, newIds[j]);
emit Arise(msg.sender, newIds[j]);
totalSupply += 1;
}
}
|
0.8.4
|
// PRIVATE HELPERS FUNCTION
|
function safeSend(address addr, uint value)
private {
if (value == 0) {
emit LOG_ZeroSend();
return;
}
if (this.balance < value) {
emit LOG_ValueIsTooBig();
return;
}
//发送资金
if (!(addr.call.gas(safeGas).value(value)())) {
emit LOG_FailedSend(addr, value);
if (addr != houseAddress) {
if (!(houseAddress.call.gas(safeGas).value(value)())) LOG_FailedSend(houseAddress, value);
}
}
emit LOG_SuccessfulSend(addr,value);
}
|
0.4.24
|
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*/
|
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
|
0.6.12
|
/**
* OZ initializer; sets the option series expiration to (block.number
* + parameter) block number; useful for tests
*/
|
function initializeInTestMode(
string calldata name,
string calldata symbol,
IERC20 _underlyingAsset,
uint8 _underlyingAssetDecimals,
IERC20 _strikeAsset,
uint256 _strikePrice) external initializer
{
_initialize(
name,
symbol,
_underlyingAsset,
_underlyingAssetDecimals,
_strikeAsset,
_strikePrice,
~uint256(0)
);
isTestingDeployment = true;
}
|
0.5.11
|
/**
* OZ initializer; sets the option series expiration to an exact
* block number
*/
|
function initialize(
string calldata name,
string calldata symbol,
IERC20 _underlyingAsset,
uint8 _underlyingAssetDecimals,
IERC20 _strikeAsset,
uint256 _strikePrice,
uint256 _expirationBlockNumber) external initializer
{
_initialize(
name,
symbol,
_underlyingAsset,
_underlyingAssetDecimals,
_strikeAsset,
_strikePrice,
_expirationBlockNumber
);
}
|
0.5.11
|
/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
/// @param to Contract address for optional delegate call.
/// @param data Data payload for optional delegate call.
/// @param fallbackHandler Handler for fallback calls to this contract
/// @param paymentToken Token that should be used for the payment (0 is ETH)
/// @param payment Value that should be paid
/// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin)
|
function setup(
address[] calldata _owners,
uint256 _threshold,
address to,
bytes calldata data,
address fallbackHandler,
address paymentToken,
uint256 payment,
address payable paymentReceiver
) external {
// setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice
setupOwners(_owners, _threshold);
if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);
// As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
setupModules(to, data);
if (payment > 0) {
// To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)
// baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment
handlePayment(payment, 0, 1, paymentToken, paymentReceiver);
}
emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);
}
|
0.7.6
|
/**
* @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise.
* @param dataHash Hash of the data (could be either a message hash or transaction hash)
* @param data That should be signed (this is passed to an external validator contract)
* @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash.
*/
|
function checkSignatures(
bytes32 dataHash,
bytes memory data,
bytes memory signatures
) public view {
// Load threshold to avoid multiple storage loads
uint256 _threshold = threshold;
// Check that a threshold is set
require(_threshold > 0, "GS001");
checkNSignatures(dataHash, data, signatures, _threshold);
}
|
0.7.6
|
/// @dev Allows to estimate a Safe transaction.
/// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data.
/// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
/// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version.
|
function requiredTxGas(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation
) external returns (uint256) {
uint256 startGas = gasleft();
// We don't provide an error message here, as we use it to return the estimate
require(execute(to, value, data, operation, gasleft()));
uint256 requiredGas = startGas - gasleft();
// Convert response to string and return via error message
revert(string(abi.encodePacked(requiredGas)));
}
|
0.7.6
|
/// @dev Returns the bytes that are hashed to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Gas that should be used for the safe transaction.
/// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash bytes.
|
function encodeTransactionData(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) public view returns (bytes memory) {
bytes32 safeTxHash =
keccak256(
abi.encode(
SAFE_TX_TYPEHASH,
to,
value,
keccak256(data),
operation,
safeTxGas,
baseGas,
gasPrice,
gasToken,
refundReceiver,
_nonce
)
);
return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);
}
|
0.7.6
|
/// @dev Returns hash to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Fas that should be used for the safe transaction.
/// @param baseGas Gas costs for data used to trigger the safe transaction.
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash.
|
function getTransactionHash(
address to,
uint256 value,
bytes calldata data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address refundReceiver,
uint256 _nonce
) public view returns (bytes32) {
return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));
}
|
0.7.6
|
//A user can withdraw its staking tokens even if there is no rewards tokens on the contract account
|
function withdraw(uint256 nonce) public override nonReentrant {
require(stakeAmounts[msg.sender][nonce] > 0, "LockStakingRewardMinAmountFixedAPY: This stake nonce was withdrawn");
require(stakeLocks[msg.sender][nonce] < block.timestamp, "LockStakingRewardMinAmountFixedAPY: Locked");
uint amount = stakeAmounts[msg.sender][nonce];
uint amountRewardEquivalent = stakeAmountsRewardEquivalent[msg.sender][nonce];
_totalSupply = _totalSupply.sub(amount);
_totalSupplyRewardEquivalent = _totalSupplyRewardEquivalent.sub(amountRewardEquivalent);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
_balancesRewardEquivalent[msg.sender] = _balancesRewardEquivalent[msg.sender].sub(amountRewardEquivalent);
stakingToken.safeTransfer(msg.sender, amount);
stakeAmounts[msg.sender][nonce] = 0;
stakeAmountsRewardEquivalent[msg.sender][nonce] = 0;
emit Withdrawn(msg.sender, amount);
}
|
0.8.0
|
/**
* Unlocks some amount of the strike token by burning option tokens.
*
* This mechanism ensures that users can only redeem tokens they've
* previously lock into this contract.
*
* Options can only be burned while the series is NOT expired.
*/
|
function burn(uint256 amount) external beforeExpiration {
require(amount <= lockedBalance[msg.sender], "Not enough underlying balance");
// Burn option tokens
lockedBalance[msg.sender] = lockedBalance[msg.sender].sub(amount);
_burn(msg.sender, amount.mul(1e18));
// Unlocks the strike token
require(strikeAsset.transfer(msg.sender, amount.mul(strikePrice)), "Couldn't transfer back strike tokens to caller");
}
|
0.5.11
|
/**
* Allow put token holders to use them to sell some amount of units
* of the underlying token for the amount * strike price units of the
* strike token.
*
* It presumes the caller has already called IERC20.approve() on the
* underlying token contract to move caller funds.
*
* During the process:
*
* - The amount * strikePrice of strike tokens are transferred to the
* caller
* - The amount of option tokens are burned
* - The amount of underlying tokens are transferred into
* this contract as a payment for the strike tokens
*
* Options can only be exchanged while the series is NOT expired.
*
* @param amount The amount of underlying tokens to be sold for strike
* tokens
*/
|
function exchange(uint256 amount) external beforeExpiration {
// Gets the payment from the caller by transfering them
// to this contract
uint256 underlyingAmount = amount * 10 ** uint256(underlyingAssetDecimals);
require(underlyingAsset.transferFrom(msg.sender, address(this), underlyingAmount), "Couldn't transfer strike tokens from caller");
// Transfers the strike tokens back in exchange
_burn(msg.sender, amount.mul(1e18));
require(strikeAsset.transfer(msg.sender, amount.mul(strikePrice)), "Couldn't transfer strike tokens to caller");
}
|
0.5.11
|
/**
* OZ initializer
*/
|
function _initialize(
string memory name,
string memory symbol,
IERC20 _underlyingAsset,
uint8 _underlyingAssetDecimals,
IERC20 _strikeAsset,
uint256 _strikePrice,
uint256 _expirationBlockNumber) private
{
ERC20Detailed.initialize(name, symbol, 18);
underlyingAsset = _underlyingAsset;
underlyingAssetDecimals = _underlyingAssetDecimals;
strikeAsset = _strikeAsset;
strikePrice = _strikePrice;
expirationBlockNumber = _expirationBlockNumber;
}
|
0.5.11
|
// Update the rewards for the given user when one or more Zillas arise
|
function updateRewardOnArise(address _user, uint256 _amount) external {
require(msg.sender == address(zillaContract), "Not the Zilla contract");
// Check the timestamp of the block against the end yield date
uint256 time = min(block.timestamp, END_YIELD);
uint256 timerUser = lastUpdate[_user];
// If one or more Zillas of the user were already minted, update the rewards to the new yield
if (timerUser > 0) {
rewards[_user] += getPendingRewards(_user,time) + (_amount * ARISE_ISSUANCE);
}
else {
rewards[_user] += _amount * ARISE_ISSUANCE;
}
// Update the mapping to the newest update
lastUpdate[_user] = time;
}
|
0.8.4
|
// Called on transfers / update rewards in the Zilla contract, allowing the new owner to get $ZILLA tokens
|
function updateReward(address _from, address _to) external {
require(msg.sender == address(zillaContract), "Not the Zilla contract");
uint256 time = min(block.timestamp, END_YIELD);
uint256 timerFrom = lastUpdate[_from];
if (timerFrom > 0) {
rewards[_from] += getPendingRewards(_from, time);
}
if (timerFrom != END_YIELD) {
lastUpdate[_from] = time;
}
if (_to != address(0)) {
uint256 timerTo = lastUpdate[_to];
if (timerTo > 0) {
rewards[_to] += getPendingRewards(_from, time);
}
if (timerTo != END_YIELD) {
lastUpdate[_to] = time;
}
}
}
|
0.8.4
|
// Mint $ZILLA tokens and send them to the user
|
function getReward(address _to) external {
require(msg.sender == address(zillaContract), "Not the Zilla contract");
uint256 reward = rewards[_to];
if (reward > 0) {
rewards[_to] = 0;
_mint(_to, reward);
emit RewardPaid(_to, reward);
}
}
|
0.8.4
|
//random number
|
function random(
uint256 from,
uint256 to,
uint256 salty
) public view returns (uint256) {
uint256 seed =
uint256(
keccak256(
abi.encodePacked(
block.timestamp +
block.difficulty +
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (block.timestamp)) +
block.gaslimit +
((uint256(keccak256(abi.encodePacked(_msgSender())))) / (block.timestamp)) +
block.number +
salty
)
)
);
return seed.mod(to - from) + from;
}
|
0.7.6
|
/// NAC Broker Presale Token
/// @dev Constructor
|
function NamiCrowdSale(address _escrow, address _namiMultiSigWallet, address _namiPresale) public {
require(_namiMultiSigWallet != 0x0);
escrow = _escrow;
namiMultiSigWallet = _namiMultiSigWallet;
namiPresale = _namiPresale;
//
balanceOf[_escrow] += 100000000000000000000000000; // 100 million NAC
totalSupply += 100000000000000000000000000;
}
|
0.4.18
|
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
|
function burnTokens(address _owner) public
onlyCrowdsaleManager
{
// Available only during migration phase
require(currentPhase == Phase.Migrating);
uint tokens = balanceOf[_owner];
require(tokens != 0);
balanceOf[_owner] = 0;
totalSupply -= tokens;
LogBurn(_owner, tokens);
// Automatically switch phase when migration is done.
if (totalSupply == 0) {
currentPhase = Phase.Migrated;
LogPhaseSwitch(Phase.Migrated);
}
}
|
0.4.18
|
/*/
* Administrative functions
/*/
|
function setPresalePhase(Phase _nextPhase) public
onlyEscrow
{
bool canSwitchPhase
= (currentPhase == Phase.Created && _nextPhase == Phase.Running)
|| (currentPhase == Phase.Running && _nextPhase == Phase.Paused)
// switch to migration phase only if crowdsale manager is set
|| ((currentPhase == Phase.Running || currentPhase == Phase.Paused)
&& _nextPhase == Phase.Migrating
&& crowdsaleManager != 0x0)
|| (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
// switch to migrated only if everyting is migrated
|| (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated
&& totalSupply == 0);
require(canSwitchPhase);
currentPhase = _nextPhase;
LogPhaseSwitch(_nextPhase);
}
|
0.4.18
|
// internal migrate migration tokens
|
function _migrateToken(address _from, address _to)
internal
{
PresaleToken presale = PresaleToken(namiPresale);
uint256 newToken = presale.balanceOf(_from);
require(newToken > 0);
// burn old token
presale.burnTokens(_from);
// add new token to _to
balanceOf[_to] = balanceOf[_to].add(newToken);
// add new token to totalSupply
totalSupply = totalSupply.add(newToken);
LogMigrate(_from, _to, newToken);
}
|
0.4.18
|
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _price price to sell token.
*/
|
function transferToExchange(address _to, uint _value, uint _price) public {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallbackExchange(msg.sender, _value, _price);
TransferToExchange(msg.sender, _to, _value, _price);
}
}
|
0.4.18
|
/**
* @dev Activates voucher. Checks nonce amount and signature and if it is correct
* send amount of tokens to caller
* @param nonce voucher's nonce
* @param amount voucher's amount
* @param signature voucher's signature
*/
|
function activateVoucher(uint256 nonce, uint256 amount, bytes signature) public {
require(!usedNonces[nonce], "nonce is already used");
require(nonce != 0, "nonce should be greater than zero");
require(amount != 0, "amount should be greater than zero");
usedNonces[nonce] = true;
address beneficiary = msg.sender;
bytes32 message = prefixed(keccak256(abi.encodePacked(
this,
nonce,
amount,
beneficiary)));
address signedBy = recoverSigner(message, signature);
require(signedBy == signerAddress);
require(token.transfer(beneficiary, amount));
emit VoucherRedemption(msg.sender, nonce, amount);
}
|
0.4.24
|
// only escrow can call
|
function resetSession()
public
onlyEscrow
{
require(!session.isReset && !session.isOpen);
session.priceOpen = 0;
session.priceClose = 0;
session.isReset = true;
session.isOpen = false;
session.investOpen = false;
session.investorCount = 0;
for (uint i = 0; i < MAX_INVESTOR; i++) {
session.investor[i] = 0x0;
session.win[i] = false;
session.amountInvest[i] = 0;
}
}
|
0.4.18
|
/// @dev Fuction for investor, minimun ether send is 0.1, one address can call one time in one session
/// @param _choose choise of investor, true is call, false is put
|
function invest (bool _choose)
public
payable
{
require(msg.value >= 100000000000000000 && session.investOpen); // msg.value >= 0.1 ether
require(now < (session.timeOpen + timeInvestInMinute * 1 minutes));
require(session.investorCount < MAX_INVESTOR && session.investedSession[msg.sender] != sessionId);
session.investor[session.investorCount] = msg.sender;
session.win[session.investorCount] = _choose;
session.amountInvest[session.investorCount] = msg.value;
session.investorCount += 1;
session.investedSession[msg.sender] = sessionId;
Invest(msg.sender, _choose, msg.value, now, sessionId);
}
|
0.4.18
|
/// @dev get amount of ether to buy NAC for investor
/// @param _ether amount ether which investor invest
/// @param _rate rate between win and loss investor
/// @param _status true for investor win and false for investor loss
|
function getEtherToBuy (uint _ether, uint _rate, bool _status)
public
pure
returns (uint)
{
if (_status) {
return _ether * _rate / 100;
} else {
return _ether * (200 - _rate) / 100;
}
}
|
0.4.18
|
/// @dev close session, only escrow can call
/// @param _priceClose price of ETH in USD
|
function closeSession (uint _priceClose)
public
onlyEscrow
{
require(_priceClose != 0 && now > (session.timeOpen + timeOneSession * 1 minutes));
require(!session.investOpen && session.isOpen);
session.priceClose = _priceClose;
bool result = (_priceClose>session.priceOpen)?true:false;
uint etherToBuy;
NamiCrowdSale namiContract = NamiCrowdSale(namiCrowdSaleAddr);
uint price = namiContract.getPrice();
for (uint i = 0; i < session.investorCount; i++) {
if (session.win[i]==result) {
etherToBuy = getEtherToBuy(session.amountInvest[i], rate, true);
} else {
etherToBuy = getEtherToBuy(session.amountInvest[i], rate, false);
}
namiContract.buy.value(etherToBuy)(session.investor[i]);
// reset investor
session.investor[i] = 0x0;
session.win[i] = false;
session.amountInvest[i] = 0;
}
session.isOpen = false;
SessionClose(now, sessionId, _priceClose, price, rate);
sessionId += 1;
// require(!session.isReset && !session.isOpen);
// reset state session
session.priceOpen = 0;
session.priceClose = 0;
session.isReset = true;
session.investOpen = false;
session.investorCount = 0;
}
|
0.4.18
|
// prevent lost ether
|
function() payable public {
require(msg.value > 0);
if (bid[msg.sender].price > 0) {
bid[msg.sender].eth = (bid[msg.sender].eth).add(msg.value);
etherBalance = etherBalance.add(msg.value);
UpdateBid(msg.sender, bid[msg.sender].price, bid[msg.sender].eth);
} else {
// refund
msg.sender.transfer(msg.value);
}
// test
// address test = "0x70c932369fc1C76fde684FF05966A70b9c1561c1";
// test.transfer(msg.value);
}
|
0.4.18
|
// prevent lost token
|
function tokenFallback(address _from, uint _value, bytes _data) public returns (bool success) {
require(_value > 0 && _data.length == 0);
if (ask[_from].price > 0) {
ask[_from].volume = (ask[_from].volume).add(_value);
nacBalance = nacBalance.add(_value);
UpdateAsk(_from, ask[_from].price, ask[_from].volume);
return true;
} else {
//refund
ERC23 asset = ERC23(NamiAddr);
asset.transfer(_from, _value);
return false;
}
}
|
0.4.18
|
// function about ask Order-----------------------------------------------------------
// place ask order by send NAC to contract
|
function tokenFallbackExchange(address _from, uint _value, uint _price) onlyNami public returns (bool success) {
require(_price > 0);
if (_value > 0) {
nacBalance = nacBalance.add(_value);
ask[_from].volume = (ask[_from].volume).add(_value);
ask[_from].price = _price;
UpdateAsk(_from, _price, ask[_from].volume);
return true;
} else {
ask[_from].price = _price;
return false;
}
}
|
0.4.18
|
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
|
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
// Transaction tx = transactions[transactionId];
transactions[transactionId].executed = true;
// tx.executed = true;
if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) {
Execution(transactionId);
} else {
ExecutionFailure(transactionId);
transactions[transactionId].executed = false;
}
}
}
|
0.4.18
|
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
|
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i = 0; i < transactionCount; i++) {
if (pending && !transactions[i].executed || executed && transactions[i].executed)
count += 1;
}
}
|
0.4.18
|
// Purchases London Ticket
|
function TicketPurchase() public payable nonReentrant whenNotPaused
{
require(_SALE_IS_ACTIVE, "Sale must be active to mint Tickets");
require(BrightList[msg.sender] > 0, "Ticket Amount Exceeds `msg.sender` Allowance");
require(_TICKET_INDEX + 1 < _MAX_TICKETS, "Purchase Would Exceed Max Supply Of Tickets");
require(_TICKET_PRICE == msg.value, "Ether Value Sent Is Not Correct. 1 ETH Per Ticket");
if(!_ALLOW_MULTIPLE_PURCHASES) { require(!purchased[msg.sender], "Address Has Already Purchased"); }
BrightList[msg.sender] -= 1;
IERC721(_TICKET_TOKEN_ADDRESS).transferFrom(_BRT_MULTISIG, msg.sender, _TICKET_INDEX);
_TICKET_INDEX += 1;
purchased[msg.sender] = true;
emit TicketPurchased(msg.sender, 1, _TICKET_INDEX);
}
|
0.8.10
|
/**
@dev Mint new token and maps to receiver
*/
|
function mint(uint256 amount, uint256 totalPrice, uint256 nonce, bytes memory signature)
external
payable
whenNotPaused
{
require(!_nonceSpended[nonce], "WabiStore: Signature already used");
require(signer.isValidSignatureNow(keccak256(abi.encodePacked(amount, msg.sender, totalPrice, nonce)), signature), "WabiStore: Invalid signature");
_nonceSpended[nonce] = true;
require(msg.value >= totalPrice, "WabiStore: msg.value is less than total price");
wabiPunks.mint(amount, msg.sender);
}
|
0.8.7
|
/**
@dev only whitelisted can buy, maximum 1
@param id - the ID of the token (eg: 1)
@param proof - merkle proof
*/
|
function presaleBuy(uint256 id, bytes32[] calldata proof) external payable nonReentrant {
require(pricesPresale[id] != 0, "not live");
require(pricesPresale[id] == msg.value, "exact amount needed");
require(block.timestamp >= presaleStartTime, "not live");
require(usedAddresses[msg.sender] + 1 <= 1, "wallet limit reached");
require(totalSupply(id) + 1 <= maxSuppliesPresale[id], "out of stock");
require(isProofValid(msg.sender, 1, proof), "invalid proof");
usedAddresses[msg.sender] += 1;
_mint(msg.sender, id, 1, "");
}
|
0.8.13
|
/**
* ######################
* # private function #
* ######################
*/
|
function toCompare(uint f, uint s) internal view returns (bool) {
if (admin.compareSymbol == "-=") {
return f > s;
} else if (admin.compareSymbol == "+=") {
return f >= s;
} else {
return false;
}
}
|
0.4.22
|
/**
@dev registers a new address for the contract name in the registry
@param _contractName contract name
@param _contractAddress contract address
*/
|
function registerAddress(bytes32 _contractName, address _contractAddress)
public
ownerOnly
validAddress(_contractAddress)
{
require(_contractName.length > 0); // validate input
if (items[_contractName].contractAddress == address(0)) {
// add the contract name to the name list
uint256 i = contractNames.push(bytes32ToString(_contractName));
// update the item's index in the list
items[_contractName].nameIndex = i - 1;
}
// update the address in the registry
items[_contractName].contractAddress = _contractAddress;
// dispatch the address update event
emit AddressUpdate(_contractName, _contractAddress);
}
|
0.4.23
|
/**
@dev removes an existing contract address from the registry
@param _contractName contract name
*/
|
function unregisterAddress(bytes32 _contractName) public ownerOnly {
require(_contractName.length > 0); // validate input
require(items[_contractName].contractAddress != address(0));
// remove the address from the registry
items[_contractName].contractAddress = address(0);
// if there are multiple items in the registry, move the last element to the deleted element's position
// and modify last element's registryItem.nameIndex in the items collection to point to the right position in contractNames
if (contractNames.length > 1) {
string memory lastContractNameString = contractNames[contractNames.length - 1];
uint256 unregisterIndex = items[_contractName].nameIndex;
contractNames[unregisterIndex] = lastContractNameString;
bytes32 lastContractName = stringToBytes32(lastContractNameString);
RegistryItem storage registryItem = items[lastContractName];
registryItem.nameIndex = unregisterIndex;
}
// remove the last element from the name list
contractNames.length--;
// zero the deleted element's index
items[_contractName].nameIndex = 0;
// dispatch the address update event
emit AddressUpdate(_contractName, address(0));
}
|
0.4.23
|
/// @notice Grant a role to a delegate
/// @dev Granting a role to a delegate will give delegate permission to call
/// contract functions associated with the role. Only owner can grant
/// role and the must be predefined and not granted to the delegate
/// already. on success, `RoleGranted` event would be fired and
/// possibly `DelegateAdded` as well if this is the first role being
/// granted to the delegate.
/// @param role the role to be granted
/// @param delegate the delegate to be granted role
|
function grantRole(bytes32 role, address delegate)
external
onlyOwner
roleDefined(role)
{
require(!_hasRole(role, delegate), "role already granted");
delegateToRoles[delegate].add(role);
// We need to emit `DelegateAdded` before `RoleGranted` to allow
// subgraph event handler to process in sensible order.
if (delegateSet.add(delegate)) {
emit DelegateAdded(delegate, _msgSender());
}
emit RoleGranted(role, delegate, _msgSender());
}
|
0.7.6
|
/// @notice Revoke a role from a delegate
/// @dev Revoking a role from a delegate will remove the permission the
/// delegate has to call contract functions associated with the role.
/// Only owner can revoke the role. The role has to be predefined and
/// granted to the delegate before revoking, otherwise the function
/// will be reverted. `RoleRevoked` event would be fired and possibly
/// `DelegateRemoved` as well if this is the last role the delegate
/// owns.
/// @param role the role to be granted
/// @param delegate the delegate to be granted role
|
function revokeRole(bytes32 role, address delegate)
external
onlyOwner
roleDefined(role)
{
require(_hasRole(role, delegate), "role has not been granted");
delegateToRoles[delegate].remove(role);
// We need to make sure `RoleRevoked` is fired before `DelegateRemoved`
// to make sure the event handlers in subgraphs are triggered in the
// right order.
emit RoleRevoked(role, delegate, _msgSender());
if (delegateToRoles[delegate].length() == 0) {
delegateSet.remove(delegate);
emit DelegateRemoved(delegate, _msgSender());
}
}
|
0.7.6
|
/// @notice Batch execute multiple transaction via Gnosis Safe
/// @dev This is batch version of the `execTransaction` function to allow
/// the delegates to bundle multiple calls into a single transaction and
/// sign only once. Batch execute the transactions, one failure cause the
/// batch reverted. Only delegates are allowed to call this.
/// @param toList list of contract addresses to be called
/// @param dataList list of input data associated with each contract call
|
function batchExecTransactions(
address[] calldata toList,
bytes[] calldata dataList
) external onlyDelegate {
require(
toList.length > 0 && toList.length == dataList.length,
"invalid inputs"
);
for (uint256 i = 0; i < toList.length; i++) {
_execTransaction(toList[i], dataList[i]);
}
}
|
0.7.6
|
/// @dev The internal implementation of `execTransaction` and
/// `batchExecTransactions`, that invokes gnosis safe to forward to
/// transaction to target contract method `to`::`func`, where `func` is
/// the function selector contained in first 4 bytes of `data`. The
/// function checks if the calling delegate has the required permission
/// to call the designated contract function before invoking Gnosis
/// Safe.
/// @param to The target contract to be called by Gnosis Safe
/// @param data The input data to be called by Gnosis Safe
|
function _execTransaction(address to, bytes memory data) internal {
bytes4 selector;
assembly {
selector := mload(add(data, 0x20))
}
require(
_hasPermission(_msgSender(), to, selector),
"permission denied"
);
// execute the transaction from Gnosis Safe, note this call will bypass
// safe owners confirmation.
require(
GnosisSafe(payable(owner())).execTransactionFromModule(
to,
0,
data,
Enum.Operation.Call
),
"failed in execution in safe"
);
emit ExecTransaction(to, 0, Enum.Operation.Call, data, _msgSender());
}
|
0.7.6
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.