comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/* * @dev return value in _binValue at position _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index index at which to retrieve value * @return Value at given _index in _bin */
function getValueInBin(uint256 _binValue, uint256 _index) internal pure returns (uint256) { // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 rightShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue >> rightShift) &...
0.5.2
// Make public for testing
function recover(address token, uint256[] memory auctionData, uint256[] memory ids, uint256[] memory amounts, bytes memory signature) internal view returns (address) { return SigUtil.recover( // This recreates the message that was signed on the client. keccak256(abi.encodePacked("\x19\x0...
0.5.2
// function sendERC777Tokens(address _from, address _to, ERC777 _tokenContract, uint256 _amount, bytes calldata _data) external { // require(msg.sender == address(this), "can only be called by own"); // _tokenContract.operatorSend(_from, _to, _amount, _data); // } // TODO safe /unsafe version // function sendER...
function executeERC20MetaTx( address _from, address _to, address _gasToken, bytes calldata _data, uint256[4] calldata params, // _nonce, _gasPrice, _txGas, _tokenGasPrice address _relayer, bytes calldata _sig, address _tokenReceiver, bool signedO...
0.5.2
//override to block from emitting Transfer when not mErc20compatible
function _send( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { callSender(_operator, _from, _to, _amount, _data, _operatorData); req...
0.5.2
/** * @dev See {IBEP1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substrin...
function uri(uint256 tokenId) public view virtual override returns (string memory ipfsmetadata) { // return _uri; Metadata memory date = token_id[tokenId]; ipfsmetadata = date.ipfsmetadata; // string memory ipfsmetadata = getmetadata(...
0.8.10
/** * @dev See {IBEP1155-safeTransferFrom}. */
function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "BEP1155: caller is not owner nor app...
0.8.10
/** * @dev See {IBEP1155-safeBatchTransferFrom}. */
function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, address(this)), "BEP1155: t...
0.8.10
/** * @dev xref:ROOT:BEP1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */
function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "BEP1155: burn from the zero address"); require( ids.length == amounts.length, "BEP1155: ids and amounts le...
0.8.10
// BNB TRANSFER PURCHASE
function saleToken( address payable from, uint256 tokenId, uint256 amount, uint256 nooftoken ) public payable { require( amount == order_place[from][tokenId].price.mul(nooftoken), "Invalid Balance" ); _saleToken(from, tokenId,...
0.8.10
// Note that address recovered from signatures must be strictly increasing, in order to prevent duplicates
function execute(uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address destination, uint value, bytes memory data, address executor, uint gasLimit) public { require(sigR.length == threshold); require(sigR.length == sigS.length && sigR.length == sigV.length); require(executor...
0.5.2
// Process a transfer internally.
function xfer(address _from, address _to, uint _amount) internal returns (bool) { require(_amount <= balances[_from]); Transfer(_from, _to, _amount); // avoid wasting gas on 0 token transfers if(_amount == 0) return true; balances[_from] = balanc...
0.4.18
// Calculates the sale and wholesale portion of tokens for a given value // of wei at the time of calling.
function ethToTokens(uint _wei) public view returns (uint allTokens_, uint wholesaleTokens_) { // Get wholesale portion of ether and tokens uint wsValueLeft = wholeSaleValueLeft(); uint wholesaleSpend = fundFailed() ? 0 : icoSu...
0.4.18
// General addresses can purchase tokens during funding
function proxyPurchase(address _addr) public payable noReentry returns (bool) { require(!fundFailed()); require(!icoSucceeded); require(now > START_DATE); require(now <= END_DATE); require(msg.value > 0); // Log ether depos...
0.4.18
// Owner can sweep a successful funding to the fundWallet. // Can be called repeatedly to recover errant ether which may have been // `selfdestructed` to the contract // Contract can be aborted up until this returns `true`
function finalizeICO() public onlyOwner preventReentry() returns (bool) { // Must have reached minimum cap require(fundRaised()); // Set first vesting date (only once as this function can be called again) if(!icoSucceeded) { nex...
0.4.18
// Bulk refunds can be pushed from a failed ICO
function refundFor(address[] _addrs) public preventReentry() returns (bool) { require(fundFailed()); uint i; uint len = _addrs.length; uint value; uint tokens; address addr; for (i; i < len; i++) { addr = _addr...
0.4.18
// // ERC20 additional and overloaded functions // // Allows a sender to transfer tokens to an array of recipients
function transferToMany(address[] _addrs, uint[] _amounts) public noReentry returns (bool) { require(_addrs.length == _amounts.length); uint len = _addrs.length; for(uint i = 0; i < len; i++) { xfer(msg.sender, _addrs[i], _amounts[i]); } ...
0.4.18
// This will selfdestruct the contract on the condittion all have been // processed.
function destroy() public noReentry onlyOwner { require(!__abortFuse); require(refunded == (etherRaised - PRESALE_ETH_RAISE)); // Log burned tokens for complete ledger accounting on archival nodes Transfer(HUT34_RETAIN, 0x0, balances[HUT34_RETAIN]); ...
0.4.18
// Calculate commission on prefunded and raised ether.
function calcCommission() internal view returns(uint) { uint commission = (this.balance + PRESALE_ETH_RAISE) / COMMISSION_DIV; // Edge case that prefund causes commission to be greater than balance return commission <= this.balance ? commission : this.balance; ...
0.4.18
/// @notice Check whether an address is a regular address or not. /// @param _addr Address of the contract that has to be checked /// @return `true` if `_addr` is a regular address (not a contract)
function isRegularAddress(address _addr) internal view returns(bool) { if (_addr == address(0)) { return false; } uint size; assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly return size == 0; }
0.5.2
/// @notice Helper function actually performing the sending of tokens. /// @param _operator The address performing the send /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _amount The number of tokens to be sent /// @param _data Data generated by the use...
function _send( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { callSender(_operator, _from, _to, _amount, _data, _operatorData); sup...
0.5.2
/// @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. /// May throw according to `_preventLocking` /// @param _operator The address performing the send or mint /// @param _from The address holding the tokens being sent /// @param _to The address of the recipient /// @param _a...
function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes memory _data, bytes memory _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensReci...
0.5.2
/// @notice Get exchange dynamic fee related keys /// @return threshold, weight decay, rounds, and max fee
function getExchangeDynamicFeeConfig() internal view returns (DynamicFeeConfig memory) { bytes32[] memory keys = new bytes32[](4); keys[0] = SETTING_EXCHANGE_DYNAMIC_FEE_THRESHOLD; keys[1] = SETTING_EXCHANGE_DYNAMIC_FEE_WEIGHT_DECAY; keys[2] = SETTING_EXCHANGE_DYNAMIC_FEE_ROUNDS; ...
0.5.16
// solhint-disable no-complex-fallback
function() external payable { // Mutable call setting Proxyable.messageSender as this is using call not delegatecall target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly for...
0.5.16
/** * SIP-139 * resets the stored value for _lastExchangeRate for multiple currencies to the latest rate * can be used to un-suspend synths after a suspension happenned * doesn't check deviations here, so believes that owner knows better * emits LastRateOverriden */
function resetLastExchangeRate(bytes32[] calldata currencyKeys) external onlyOwner { (uint[] memory rates, bool anyRateInvalid) = _exchangeRates().ratesAndInvalidForCurrencies(currencyKeys); require(!anyRateInvalid, "Rates for given synths not valid"); for (uint i = 0; i < currencyKeys.length;...
0.5.16
/** * Rate is invalid if: * - is outside of deviation bounds relative to previous non-zero rate * - (warm up case) if previous rate was 0 (init), gets last 4 rates from oracle, and checks * if rate is outside of deviation w.r.t any of the 3 previous ones (excluding the last one). */
function _isRateOutOfBounds(bytes32 currencyKey, uint currentRate) internal view returns (bool) { if (currentRate == 0) { return true; } uint lastRateFromExchange = _lastExchangeRate[currencyKey]; if (lastRateFromExchange > 0) { return _isDeviationAboveThreshold...
0.5.16
/** * @notice Gets the strike price by multiplying the current underlying price * with a multiplier * @param expiryTimestamp is the unix timestamp of expiration * @param isPut is whether option is put or call * @return newStrikePrice is the strike price of the option (ex: for BTC might be 45000 * 10 ** 8) * @retu...
function getStrikePrice(uint256 expiryTimestamp, bool isPut) external view returns (uint256 newStrikePrice, uint256 newDelta) { require( expiryTimestamp > block.timestamp, "Expiry must be in the future!" ); // asset price uint256 strik...
0.8.4
// TODO could potentialy get ir fo this and use operatorSend instead (the token contract itself could be an defaultOperator)
function sendFrom(address _from, address _to, uint256 _amount, bytes calldata _data) external { require(msg.sender == address(this), "only to be used by contract to support meta-tx"); // allow _from to allow gas estimatiom _send(_from, _from, _to, _amount, _data, "", true); }
0.5.2
/* Transfer the balance from the sender's address to the address _to */
function transfer(address _to, uint256 _value) public returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_val...
0.4.24
/* Withdraws to address _to form the address _from up to the amount _value */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { balances[_from] = balances[_from...
0.4.24
// Only the liqMiningEmergencyHandler can call this function, when its in emergencyMode // this will allow a spender to spend the whole balance of the specified tokens from this contract // as well as to spend tokensForLpHolder from the respective lp holders for expiries specified // the spender should ideally be a con...
function setUpEmergencyMode(uint256[] calldata expiries, address spender) external override { (, bool emergencyMode) = pausingManager.checkLiqMiningStatus(address(this)); require(emergencyMode, "NOT_EMERGENCY"); (address liqMiningEmergencyHandler, , ) = pausingManager.liqMiningEmergencyHandler(...
0.7.6
/** * @notice fund new epochs * @dev Once the last epoch is over, the program is permanently override * @dev the settings must be set before epochs can be funded => if funded=true, means that epochs have been funded & have already has valid allocation settings * conditions: * Must only be called by governance */
function fund(uint256[] calldata _rewards) external override onlyGovernance { checkNotPaused(); // Can only be fund if there is already a setting require(latestSetting.id > 0, "NO_ALLOC_SETTING"); // Once the program is over, cannot fund require(_getCurrentEpochId() <= numberOfEp...
0.7.6
/** @notice top up rewards for any funded future epochs (but not to create new epochs) * conditions: * Must only be called by governance * The contract must have been funded already */
function topUpRewards(uint256[] calldata _epochIds, uint256[] calldata _rewards) external override onlyGovernance isFunded { checkNotPaused(); require(latestSetting.id > 0, "NO_ALLOC_SETTING"); require(_epochIds.length == _rewards.length, "INVALID_ARRAYS"); ...
0.7.6
/** @notice set a new allocation setting, which will be applied from the next epoch onwards @dev all the epochData from latestSetting.firstEpochToApply+1 to current epoch will follow the previous allocation setting @dev We must set the very first allocation setting before the start of epoch 1, otherwise epoch 1 w...
function setAllocationSetting( uint256[] calldata _expiries, uint256[] calldata _allocationNumerators ) external onlyGovernance { checkNotPaused(); require(_expiries.length == _allocationNumerators.length, "INVALID_ALLOCATION"); if (latestSetting.id == 0) { requir...
0.7.6
/** * @notice Similar to stake() function, but using a permit to approve for LP tokens first */
function stakeWithPermit( uint256 expiry, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override isFunded nonReentrant nonContractOrWhitelisted returns (address newLpHoldingContractAddress) ...
0.7.6
/** * @notice Use to withdraw their LP from a specific expiry Conditions: * only be called if the contract has been funded. * must have Reentrancy protection * only be called if 0 < current epoch (always can withdraw) */
function withdraw(uint256 expiry, uint256 amount) external override nonReentrant isFunded { checkNotPaused(); uint256 curEpoch = _getCurrentEpochId(); require(curEpoch > 0, "NOT_STARTED"); require(amount != 0, "ZERO_AMOUNT"); ExpiryData storage exd = expiryData[expiry]; ...
0.7.6
/** * @notice use to claim PENDLE rewards Conditions: * only be called if the contract has been funded. * must have Reentrancy protection * only be called if 0 < current epoch (always can withdraw) * Anyone can call it (and claim it for any other user) */
function redeemRewards(uint256 expiry, address user) external override isFunded nonReentrant returns (uint256 rewards) { checkNotPaused(); uint256 curEpoch = _getCurrentEpochId(); require(curEpoch > 0, "NOT_STARTED"); require(user != address(0)...
0.7.6
/** @notice update the following stake data for the current epoch: - epochData[_curEpoch].stakeUnitsForExpiry - epochData[_curEpoch].lastUpdatedForExpiry @dev If this is the very first transaction involving this expiry, then need to update for the previous epoch as well. If the previous didn't have any transaction...
function _updateStakeDataForExpiry(uint256 expiry) internal { uint256 _curEpoch = _getCurrentEpochId(); // loop through all epochData in descending order for (uint256 i = Math.min(_curEpoch, numberOfEpochs); i > 0; i--) { uint256 epochEndTime = _endTimeOfEpoch(i); uint25...
0.7.6
// calc the amount of rewards the user is eligible to receive from this epoch // but we will return the amount per vestingEpoch instead
function _calcAmountRewardsForUserInEpoch( uint256 expiry, address user, uint256 epochId ) internal view returns (uint256 rewardsPerVestingEpoch) { uint256 settingId = epochId >= latestSetting.firstEpochToApply ? latestSetting.id : epochDat...
0.7.6
/** * @notice returns the stakeUnits in the _epochId(th) epoch of an user if he stake from _startTime to now * @dev to calculate durationStakeThisEpoch: * user will stake from _startTime -> _endTime, while the epoch last from _startTimeOfEpoch -> _endTimeOfEpoch * => the stakeDuration of user will be min(_endTi...
function _calcUnitsStakeInEpoch( uint256 lpAmount, uint256 _startTime, uint256 _epochId ) internal view returns (uint256 stakeUnitsForUser) { uint256 _endTime = block.timestamp; uint256 _l = Math.max(_startTime, _startTimeOfEpoch(_epochId)); uint256 _r = Math.min(_en...
0.7.6
/** @notice Calc the amount of rewards that the user can receive now. @dev To be called before any rewards is transferred out */
function _beforeTransferPendingRewards(uint256 expiry, address user) internal returns (uint256 amountOut) { _updatePendingRewards(expiry, user); uint256 _lastEpoch = Math.min(_getCurrentEpochId(), numberOfEpochs + vestingEpochs); for (uint256 i = expiryData[expiry].lastEpoch...
0.7.6
/** * @dev all LP interests related functions are almost identical to markets' functions * Very similar to the function in PendleMarketBase. Any major differences are likely to be bugs Please refer to it for more details */
function _updateParamL(uint256 expiry) internal { ExpiryData storage exd = expiryData[expiry]; if (!checkNeedUpdateParamL(expiry)) return; IPendleLpHolder(exd.lpHolder).redeemLpInterests(); uint256 currentNYield = IERC20(underlyingYieldToken).balanceOf(exd.lpHolder); (uint256 ...
0.7.6
/** * @dev Creates a new voting proposal for the execution `_transaction` of `_targetContract`. * Only voter can create a new proposal. * * Emits a `ProposalStarted` event. * * Requirements: * * - `_targetContract` cannot be the zero address. * - `_transaction` length must not be less than 4 bytes. ...
function newProposal( address _targetContract, bytes memory _transaction ) public onlyVoter { require(_targetContract != address(0), "Address must be non-zero"); require(_transaction.length >= 4, "Tx must be 4+ bytes"); // solhint-disable not-rely-on-time bytes32 _proposalHash = kecc...
0.5.10
/** * @dev Adds sender's vote to the proposal and then follows the majority voting algoritm. * * Emits a `Vote` event. * * Requirements: * * - proposal with `_proposalHash` must not be finished. * - sender must not be already voted. * * @notice Vote "for" or "against" in proposal with `_proposalHash...
function vote(bytes32 _proposalHash, bool _yes) public onlyVoter { // solhint-disable code-complexity require(!proposals[_proposalHash].finished, "Already finished"); require(!proposals[_proposalHash].votedFor[msg.sender], "Already voted"); require(!proposals[_proposalHash].votedAgainst[msg.s...
0.5.10
/** * @dev Removes `_address` from the voters list. * This method can be executed only via proposal of this Governance contract. * * Emits a `delVoter` event. * * Requirements: * * - `_address` must be in voters list. * - Num of voters must be more than one. * * @param _address Address of voter to...
function delVoter(address _address) public onlyMe { require(isVoter[_address], "Not in voters list"); require(votersCount > 1, "Can not delete single voter"); for (uint256 i = 0; i < voters.length; i++) { if (voters[i] == _address) { if (voters.length > 1) { ...
0.5.10
// payout for claiming
function payouts(address payable _to, uint256 _amount, address token) external onlyOperator { require(_to != address(0),"_to is zero"); if (token != ETHEREUM) { IERC20(token).safeTransfer(_to, _amount); } else { _to.transfer(_amount); } emit ePay...
0.6.12
// burn 1/2 for claiming
function burnOuts(address[] calldata _burnUsers, uint256[] calldata _amounts) external onlyOperator { require(_burnUsers.length == _amounts.length, "not equal"); for(uint256 i = 0; i<_burnUsers.length; i++) { require(_balances[_burnUsers[i]] >= _amounts[i], "insufficient...
0.6.12
/* * FEE: * 1 = 0.001% * 1000 = 1% * 100000 = 100% */
function setFeeDistributions(address _token, address _feeWallet, string memory _name, uint256 _percent) public onlyOwner { require(_token != address(0), "address not valid"); require(_feeWallet != address(0), "address not valid"); _Fee[] storage fees = feeDistributions[_token]; //...
0.5.0
/** * @dev users can invoke this function to open a new pool. * @param _token the ERC20 token of the reward. * @param _reward the amount of reward. * @param _weight determines how the pool ranks in frontend. * @param _expiry the timestamp the pool expires. when a pool expires * the owner will have to pay to...
function openNewPool (IERC20 _token, address _currencyToken, uint112 _exchangeRate, uint _reward, uint _weight, uint64 _expiry, bytes32 name) external returns (uint pid){ // require (_weight >= minPoolCost, "Need more YouBetToken"); address poolOwner = msg.sender; _reward = _safeTokenTransfer(...
0.6.12
/** * @dev users can invoke this function to purchase tokens. * @param _pid the pool id where the user is purchasing * @param _purchaseAmount amount in token to purchase **/
function buyTokenWithETH (uint _pid, uint _purchaseAmount, address referrer) external payable { address _customer = msg.sender; require (pools[_pid].status == PoolStatus.OPEN, "lottery pool not open"); require (now < pools[_pid].expiry, "lottery pool expired"); IERC20 _pooltoken = IERC20(poo...
0.6.12
/** * @dev allows anyone to draw the winning ticket for an eligible pool. * @param _pid the pool id where user is drawing. **/
function closePool (uint _pid) external { address _poolOwner = pools[_pid].owner; require (pools[_pid].status==PoolStatus.OPEN, "Pool must be open"); require (_poolOwner==msg.sender||msg.sender==owner(), "unauthorized"); IERC20 _pooltoken = IERC20(pools[_pid].token); IERC20 _poolCurrencyT...
0.6.12
// function transferFrom(address _from, address _to, uint256 _id, uint256 _value) external { // _transferFrom(_from, _to, _id, _value); // }
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external { _transferFrom(_from, _to, _id, _value); require(_checkERC1155AndCallSafeTransfer(msg.sender == address(_sandContract) ? _from : msg.sender, _from, _to, _id, _value, _data, false, false)); ...
0.5.2
// function batchTransferFrom(address _from, address _to, uint256[]calldata _ids, uint256[] calldata _values) external { // _batchTransferFrom(_from, _to, _ids, _values); // }
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external { _batchTransferFrom(_from, _to, _ids, _values); require(_checkERC1155AndCallSafeBatchTransfer(msg.sender == address(_sandContract) ? _from : msg.sender, _from, ...
0.5.2
// TODO enable ?
function extractERC721(address _sender, uint256 _id, string calldata _uri) external { require(msg.sender == _sender || msg.sender == address(_sandContract) || mSuperOperators[msg.sender], "require meta approval"); require(erc1155_metadataURIHashes[_id] != 0, "Not an ERC1155 Token"); require(erc1...
0.5.2
/** * @dev transfer token for a specified address with froze status checking * @param _toMulti The addresses to transfer to. * @param _values The array of the amount to be transferred. */
function transferMultiAddress(address[] _toMulti, uint256[] _values) public whenNotPaused returns (bool) { require(!frozenAccount[msg.sender]); assert(_toMulti.length == _values.length); uint256 i = 0; while ( i < _toMulti.length) { require(_toMulti[i] != address(0)); require(_va...
0.4.19
/** * @dev Transfer tokens from one address to another with checking the frozen status * @param _from address The address which you want to send tokens from * @param _toMulti address[] The addresses which you want to transfer to in boundle * @param _values uint256[] the array of amount of tokens to be transferr...
function transferMultiAddressFrom(address _from, address[] _toMulti, uint256[] _values) public whenNotPaused returns (bool) { require(!frozenAccount[_from]); assert(_toMulti.length == _values.length); uint256 i = 0; while ( i < _toMulti.length) { require(_toMulti[i] != address(0)); ...
0.4.19
// Tokens sold by crowdsale contract will be frozen ultil crowdsale ends
function txAllowed(address sender, uint256 amount) private returns (bool isAllowed) { if (timelock[sender] > block.timestamp) { return isBalanceFree(sender, amount); } else { if (frozenBalances[sender] > 0) frozenBalances[sender] = 0; return true; } ...
0.7.4
/* Current code intentionally prevents governance re-initialization. This may be a problem in an upgrade situation, in a case that the upgrade-to implementation performs an initialization (for real) and within that calls initGovernance(). Possible workarounds: 1. Clearing the governance info altogether by changi...
function initGovernance() internal { string memory tag = getGovernanceTag(); GovernanceInfoStruct storage gub = governanceInfo[tag]; // TODO(Remo,01/09/2021): Consider un-commenting lines below. // if (gub.initialized) { // return; // } require(!gu...
0.6.11
/* Send tokens */
function transfer(address _to, uint256 _value) public returns(bool){ if (_to == 0x0) return false; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) return false; if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough ...
0.4.26
/* Transfer tokens */
function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) { if (_to == 0x0) revert(); // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) revert(); if (balanceOf[_from] < _value) revert(); // Check if ...
0.4.26
/* Destruction of the token */
function burn(uint256 _value) public returns(bool success) { if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSuppl...
0.4.26
/// @dev Cancels the input order. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @param cancelTakerTokenAmount Desired amount of tak...
function cancelOrder( address[5] orderAddresses, uint[6] orderValues, uint cancelTakerTokenAmount) public onlyWhitelisted returns (uint) { Order memory order = Order({ maker: orderAddresses[0], taker: orderAddresses[1], ...
0.4.18
/// @dev Synchronously executes multiple fill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmounts Array of desired amounts of takerToken t...
function batchFillOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillTakerTokenAmounts, bool shouldThrowOnInsufficientBalanceOrAllowance, uint8[] v, bytes32[] r, bytes32[] s) public { for (uint i = 0; i < orderAddr...
0.4.18
/// @dev Synchronously executes multiple fillOrKill orders in a single transaction. /// @param orderAddresses Array of address arrays containing individual order addresses. /// @param orderValues Array of uint arrays containing individual order values. /// @param fillTakerTokenAmounts Array of desired amounts of takerT...
function batchFillOrKillOrders( address[5][] orderAddresses, uint[6][] orderValues, uint[] fillTakerTokenAmounts, uint8[] v, bytes32[] r, bytes32[] s) public { for (uint i = 0; i < orderAddresses.length; i++) { fillOrKillOrder( ...
0.4.18
/// @dev Calculates Keccak-256 hash of order with specified parameters. /// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient. /// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt. /// @return Kecca...
function getOrderHash(address[5] orderAddresses, uint[6] orderValues) public constant returns (bytes32) { return keccak256( address(this), orderAddresses[0], // maker orderAddresses[1], // taker orderAddresses[2], // makerToken...
0.4.18
/// @dev Checks if rounding error > 0.1%. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present.
function isRoundingError(uint numerator, uint denominator, uint target) public constant returns (bool) { uint remainder = mulmod(target, numerator, denominator); if (remainder == 0) return false; // No rounding error. uint errPercentageTimes1000000 = safeDiv(...
0.4.18
/// @dev Get token balance of an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Token balance of owner.
function getBalance(address token, address owner) internal constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. returns (uint) { return Token(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); // Limit gas to ...
0.4.18
/// @dev Get allowance of token given to TokenTransferProxy by an address. /// @param token Address of token. /// @param owner Address of owner. /// @return Allowance of token given to TokenTransferProxy by owner.
function getAllowance(address token, address owner) internal constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit. returns (uint) { return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_...
0.4.18
/** * @dev Decreaese locking time * @param _affectiveAddress Address of the locked address * @param _decreasedTime Time in days to be affected */
function decreaseLockingTimeByAddress(address _affectiveAddress, uint _decreasedTime) external onlyOwner returns(bool){ require(_decreasedTime > 0 && time[_affectiveAddress] > now, "Please check address status or Incorrect input"); time[_affectiveAddress] = time[_affectiveAddress] - (_decreasedTim...
0.5.8
/** * @dev Increase locking time * @param _affectiveAddress Address of the locked address * @param _increasedTime Time in days to be affected */
function increaseLockingTimeByAddress(address _affectiveAddress, uint _increasedTime) external onlyOwner returns(bool){ require(_increasedTime > 0 && time[_affectiveAddress] > now, "Please check address status or Incorrect input"); time[_affectiveAddress] = time[_affectiveAddress] + (_increasedTim...
0.5.8
/// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The a...
function positions(uint256 tokenId) external view returns ( uint96 nonce, // [0] address operator, // [1] address token0, // [2] address token1, // [3] uint24 fee, // [4] int24 tickLower, // [5] int24 t...
0.6.12
/** * @dev add liquidity to LP */
function _adLp(uint256 ethAmount, address tokenAddress) private returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ) { uint256 reserveA; uint256 reserveB; (reserveA, reserveB) = UniswapV2Library.getReser...
0.6.6
/** * @dev update the internal list of purchases */
function _updateBalance(uint256 ethAmount, uint256 vPUREAmount) private { _vCrowdsaleBalance[msg.sender].ethAmount = _vCrowdsaleBalance[msg .sender] .ethAmount .add(ethAmount); // safetly check for the total amount of ETH bought by a single user // it sh...
0.6.6
/// @inheritdoc IPeripheryPaymentsWithFee
function unwrapWETH9WithFee( uint256 amountMinimum, address recipient, uint256 feeBips, address feeRecipient ) public payable override { require(feeBips > 0 && feeBips <= 100); uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this)); require(balanceWETH...
0.7.6
/// @dev presale mint for whitelisted
function presalemint(uint256 tokens, bytes32[] calldata merkleProof) public payable { require(!paused, "SHIBNFT: oops contract is paused"); require(preSale, "SHIBNFT: Presale Hasn't started yet"); require(MerkleProof.verify(merkleProof, merkleRoot, keccak256(abi.encodePacked(msg.sender))), "SHIBNFT: You...
0.8.7
/// @dev use it for giveaway and mint for yourself
function gift(uint256 _mintAmount, address destination) public onlyOwner { require(_mintAmount > 0, "need to mint at least 1 NFT"); uint256 supply = totalSupply(); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); _safeMint(destination, _mintAmount); }
0.8.7
/** * @notice Migrate all funds from old strategy to new strategy * Requirements: * - Only owner of this contract call this function * - This contract is not locked * - Pending strategy is set */
function migrateFunds() external onlyOwner { require( unlockTime <= block.timestamp && unlockTime + 1 days >= block.timestamp, "Function locked" ); require( token.balanceOf(address(strategy)) > 0, "No balance to migrate" ); ...
0.7.6
/***************************************************************************** * Well done, you found it. Now can you solve the puzzle and become a student? * If you do pass, how good a student will you be? * * * Notes: * * Be careful sharing or copying answers, they need to be personalised * for each studen...
function mint( bytes32 _personalisedAnswer1, bytes32 _personalisedAnswer2, bytes32 _personalisedAnswer3, bytes32 _personalisedAnswer4, bytes32 _personalisedAnswer5 ) external payable { if (msg.sender.isContract()) { revert NoContractCall(); } ...
0.8.9
// Optional: Give your student a name and it will appear in the image. // Free but you'll have to pay gas. // Name must be 1-12 alphanumeric characters or space.
function setStudentName(string calldata _studentName, uint256 _tokenId) external { if (msg.sender != ownerOf(_tokenId)) revert NotOwnerOfToken(); bytes memory nameBytes = bytes(_studentName); uint256 nameLength = nameBytes.length; if (nameLength == 0) revert InvalidName(); if (na...
0.8.9
/***************************************************************** ************************ Future puzzles ************************* * Some puzzles will be free (enter 0 in the amount field) * although you can donate if you are enjoying the school. * More complex puzzles and metadata that take us considerable * ...
function attemptPuzzle( uint256 _tokenId, uint _puzzleIndex, bytes32 _personalisedAnswer1, bytes32 _personalisedAnswer2, bytes32 _personalisedAnswer3, bytes32 _personalisedAnswer4, bytes32 _personalisedAnswer5 ) external payable { if (msg.sender.isCont...
0.8.9
/** * @notice Determines if the byte encoded description of a position(s) is valid. * The description will only make sense in context of the product. * @dev This function should be overwritten in inheriting Product contracts. * @param positionDescription The description to validate. * @return isValid True if is va...
function isValidPositionDescription(bytes memory positionDescription) public view virtual override returns (bool isValid) { // check length // solhint-disable-next-line var-name-mixedcase uint256 ADDRESS_SIZE = 20; // must be concatenation of one or more addresses if (positionDes...
0.8.6
/** * @dev Wipes the balance of a frozen address, burning the tokens * and setting the approval to zero. * @param _addr The new frozen address to wipe. */
function wipeFrozenAddress(address _addr) public onlyLawEnforcementRole { require(frozen[_addr], "address is not frozen"); uint256 _balance = balances[_addr]; balances[_addr] = 0; totalSupply_ = totalSupply_.sub(_balance); emit FrozenAddressWiped(_addr); emit SupplyDecrea...
0.4.24
/** * @dev Sets a new supply controller address. * @param _newSupplyController The address allowed to burn/mint tokens to control supply. */
function setSupplyController(address _newSupplyController) public { require(msg.sender == supplyController || msg.sender == owner, "only SupplyController or Owner"); require(_newSupplyController != address(0), "cannot set supply controller to address zero"); emit SupplyControllerSet(supplyContro...
0.4.24
/** * @dev Decreases the total supply by burning the specified number of tokens from the supply controller account. * @param _value The number of tokens to remove. * @return A boolean that indicates if the operation was successful. */
function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) { require(_value <= balances[supplyController], "not enough supply"); balances[supplyController] = balances[supplyController].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit SupplyDecrea...
0.4.24
/// @return Returns index and ok for the first occurrence starting from /// index 0
function index(address[] addresses, address a) internal pure returns (uint, bool) { for (uint i = 0; i < addresses.length; i++) { if (addresses[i] == a) { return (i, true); } } return (0, false); }
0.4.21
/// @notice Initializes contract with a list of ERC20 token addresses and /// corresponding minimum number of units required for a creation unit /// @param addresses Addresses of the underlying ERC20 token contracts /// @param quantities Number of token base units required per creation unit /// @param _creationUnit Num...
function BsktToken( address[] addresses, uint256[] quantities, uint256 _creationUnit, string _name, string _symbol ) DetailedERC20(_name, _symbol, 18) public { require(addresses.length > 0); require(addresses.length == quantities.length); requ...
0.4.21
/// @notice Creates Bskt tokens in exchange for underlying tokens. Before /// calling, underlying tokens must be approved to be moved by the Bskt /// contract. The number of approved tokens required depends on baseUnits. /// @dev If any underlying tokens' `transferFrom` fails (eg. the token is /// frozen), create will ...
function create(uint256 baseUnits) external whenNotPaused() requireNonZero(baseUnits) requireMultiple(baseUnits) { // Check overflow require((totalSupply_ + baseUnits) > totalSupply_); for (uint256 i = 0; i < tokens.length; i++) { TokenI...
0.4.21
/// @notice Redeems Bskt tokens in exchange for underlying tokens /// @param baseUnits Number of base units to redeem. Must be a multiple of /// creationUnit. /// @param tokensToSkip Underlying token addresses to skip redemption for. /// Intended to be used to skip frozen or broken tokens which would prevent /// all un...
function redeem(uint256 baseUnits, address[] tokensToSkip) external requireNonZero(baseUnits) requireMultiple(baseUnits) { require(baseUnits <= totalSupply_); require(baseUnits <= balances[msg.sender]); require(tokensToSkip.length <= tokens.length); //...
0.4.21
// @notice Look up token quantity and whether token exists // @param token Token address to look up // @return (quantity, ok) Units of underlying token, and whether the // token was found
function getQuantity(address token) internal view returns (uint256, bool) { for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i].addr == token) { return (tokens[i].quantity, true); } } return (0, false); }
0.4.21
/// @notice Owner: Withdraw excess funds which don't belong to Bskt token /// holders /// @param token ERC20 token address to withdraw
function withdrawExcessToken(address token) external onlyOwner nonReentrant { ERC20 erc20 = ERC20(token); uint256 withdrawAmount; uint256 amountOwned = erc20.balanceOf(address(this)); uint256 quantity; bool ok; (quantity, ok) = getQua...
0.4.21
// Purchase one or more card packs for the price in ToshiCoin
function purchasePack(uint256 amount) public { require(packPriceInToshiCoin > 0, 'Pack does not exist'); require( toshiCoin.balanceOf(msg.sender) >= packPriceInToshiCoin.mul(amount), 'Not enough toshiCoin for pack' ); toshiCoin.burn(msg.sender, packPriceInToshiCoin.mul(amount)); ...
0.6.12
// Utility function to check if a value is inside an array
function _isInArray(uint256 _value, uint256[] memory _array) internal pure returns (bool) { uint256 length = _array.length; for (uint256 i = 0; i < length; ++i) { if (_array[i] == _value) { return true; } } return false; }
0.6.12
/* send Tokens to any investor by owner or distributor */
function sendToInvestor(address investor, uint value) public canTransfer { require(investor != 0x0 && value > 0); require(value <= balances[owner]); /* new */ require(distributorsAmount[msg.sender] >= value && value > 0); distributorsAmount[msg.sender] = distributorsAmount[msg.sender].sub(v...
0.4.24
/* transfer method, with byuout */
function transfer(address to, uint value) public returns (bool success) { require(to != 0x0 && value > 0); if(to == owner && byuoutActive && byuoutCount > 0){ uint bonus = 0 ; if(value > byuoutCount){ bonus = byuoutCount.mul(priceForBasePart); ...
0.4.24
/// @notice All governing tokens created via factory. /// @return array of all governing token addresses.
function poolTokens() public view returns (address[] memory) { uint256 length = _poolTokens.length(); address[] memory poolTokenAddresses = new address[](length); for (uint256 i = 0; i < length; i++) { poolTokenAddresses[i] = _poolTokens.at(i); } return poolTokenAddresses; }
0.6.6
/// @notice Gets addresses of governing tokens that are visible to holder. /// @param holder_ holder address to get available tokens for. /// @return array of token addresses that holder owns or can buy.
function poolTokensForHolder(address holder_) public view returns (address[] memory) { uint256 length = _poolTokens.length(); if (length == 0) { return new address[](0); } address[] memory poolTokenAddresses = new address[](length); uint256 pointer = 0; for (uint256 i = 0; i < length; i++)...
0.6.6
/// @notice Checks whether provided address is a valid DAO. /// @param dao_ address to check. /// @return bool true if address is a valid DAO.
function isDao(address dao_) public view override returns (bool) { if (dao_ == _torroDao) { return true; } uint256 length = _poolTokens.length(); for (uint256 i = 0; i < length; i++) { if (dao_ == _pools[_poolTokens.at(i)]) { return true; } } return false; }
0.6.6
/// @notice Creates a cloned DAO and governing token. /// @param maxCost_ maximum cost of all governing tokens for created DAO. /// @param executeMinPct_ minimum percentage of votes needed for proposal execution. /// @param votingMinHours_ minimum lifetime of proposal before it closes. /// @param isPublic_ whether DAO ...
function create(uint256 maxCost_, uint256 executeMinPct_, uint256 votingMinHours_, bool isPublic_, bool hasAdmins_) public payable { // Check that correct payment has been sent for creation. require(msg.value == _createPrice); // Check that maximum cost specified is equal or greater than required minimal ma...
0.6.6
/// @notice Claim available benefits for holder. /// @param amount_ of wei to claim.
function claimBenefits(uint256 amount_) public override { // Check that factory has enough eth to pay for withdrawal. require(amount_ <= address(this).balance); // Check that holder has enough benefits to withdraw specified amount. uint256 amount = _benefits[msg.sender]; require(amount_ >= amount); ...
0.6.6
/// @notice Adds withdrawal benefits for holder. /// @param recipient_ holder that's getting benefits. /// @param amount_ benefits amount to be added to holder's existing benefits.
function addBenefits(address recipient_, uint256 amount_) public override { // Check that function is triggered by one of DAO governing tokens. require(_torroToken == msg.sender || _poolTokens.contains(msg.sender)); // Add holders benefits. _benefits[recipient_] = _benefits[recipient_] + amount_; }
0.6.6
/// @notice Depositis withdrawal benefits. /// @param token_ governing token for DAO that's depositing benefits.
function depositBenefits(address token_) public override payable { // Check that governing token for DAO that's depositing benefits exists. // And check that benefits deposition is sent by corresponding DAO. if (token_ == _torroToken) { require(msg.sender == _torroDao); } else { require(_poo...
0.6.6