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));
... | 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 de... | 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 jus... | 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);
... | 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.... | 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]);
dragonMark... | 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).supportsInt... | 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).supportsI... | 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 `... | 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 airdro... | 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 ... | 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)) {
FundTra... | 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_[_customerA... | 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, _val... | 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); ... | 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) _... | 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)
... | 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.balanc... | 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) {
... | 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] +... | 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... | 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(_... | 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.time... | 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 ... | 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++) {
... | 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 paus... | 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 l... | 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 ... | 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+... | 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<... | 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< cont... | 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 =... | 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_pla... | 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=r... | 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 =... | 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;
... | 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), targetBy... | 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 = IALCX... | 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(ex... | 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, amou... | 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); // S... | 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)... | 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)] = _overn... | 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]... | 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] = _ownerSigTo... | 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;
... | 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... | 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... | 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));
... | 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... | 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 == o... | 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 = IUniswapV2P... | 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[se... | 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
addr... | 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);
em... | 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
uint25... | 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... | 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");
... | 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... | 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(s... | 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,
... | 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,... | 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 ... | 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... | 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 d... | 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");
... | 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 ... | 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, val... | 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 independ... | 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 retur... | 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 transact... | 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 ... | 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 amou... | 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 ... | 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 ... | 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), underlying... | 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);
... | 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 = lastUp... | 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] += getPendin... | 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)) +
... | 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] += 100000000000000... | 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;
... | 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 cro... | 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
... | 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 ... | 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);
... | 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 = m... | 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.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.invested... | 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... | 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);
... | 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);
UpdateA... | 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 = _p... | 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;
i... | 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 Sup... | 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))... | 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 lim... | 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 ... | 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);
... | 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 ... | 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
// sub... | 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, other... | 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`... | 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. O... | 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++) {
... | 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 ca... | 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 transactio... | 0.7.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.