comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/// @dev allows the owner to remove the fees paid into this contract for minting /// @param feeTokenAddress - address of the erc20 token fees have been paid in /// @param feeRecipient - Recipient address of fees
function withdrawFees(address feeTokenAddress, address feeRecipient) public onlyOwner { uint feesAvailableForWithdrawal = feesCollectedByTokenAddress[feeTokenAddress]; require(feesAvailableForWithdrawal != 0, "No fees available for withdrawal"); require(feeRecipient != address(0), "Cannot sen...
0.5.2
/** * @dev Print number of block till next expected dividend payment */
function dividendsBlocks() constant external returns (uint) { if(investStart > 0) { return(0); } uint period = (block.number - hashFirst) / (10 * hashesSize); if(period > dividendPeriod) { return(0); } return((10 * hashesSize) - ((block.num...
0.4.17
/** * @dev Move funds to cold storage * @dev investBalance and walletBalance is protected from withdraw by owner * @dev if funding is > 50% admin can withdraw only 0.25% of balance weekly * @param _amount The amount of wei to move to cold storage */
function coldStore(uint _amount) external onlyOwner { houseKeeping(); require(_amount > 0 && this.balance >= (investBalance * 9 / 10) + walletBalance + _amount); if(investBalance >= investBalanceGot / 2){ // additional jackpot protection require((_amount <= this.balance / 400) &&...
0.4.17
/** * @dev Update accounting */
function houseKeeping() public { if(investStart > 1 && block.number >= investStart + (hashesSize * 5)){ // ca. 14 days investStart = 0; // start dividend payments } else { if(hashFirst > 0){ uint period = (block.number - hashFirst) / (10 * hashesSize ); ...
0.4.17
/** * @dev Delete all tokens owned by sender and return unpaid dividends and 90% of initial investment */
function disinvest() external { require(investStart == 0); commitDividend(msg.sender); uint initialInvestment = balances[msg.sender] * 10**15; Transfer(msg.sender,address(0),balances[msg.sender]); // for etherscan delete balances[msg.sender]; // totalSupply stays the same, i...
0.4.17
/** * @dev Commit remaining dividends before transfer of tokens */
function commitDividend(address _who) internal { uint last = wallets[_who].lastDividendPeriod; if((balances[_who]==0) || (last==0)){ wallets[_who].lastDividendPeriod=uint16(dividendPeriod); return; } if(last==dividendPeriod) { return; }...
0.4.17
/* lottery functions */
function betPrize(Bet _player, uint24 _hash) constant private returns (uint) { // house fee 13.85% uint24 bethash = uint24(_player.betHash); uint24 hit = bethash ^ _hash; uint24 matches = ((hit & 0xF) == 0 ? 1 : 0 ) + ((hit & 0xF0) == 0 ? 1 : 0 ) + ((hit...
0.4.17
/** * @dev Check if won in lottery */
function betOf(address _who) constant external returns (uint) { Bet memory player = bets[_who]; if( (player.value==0) || (player.blockNum<=1) || (block.number<player.blockNum) || (block.number>=player.blockNum + (10 * hashesSize))){ return(0); ...
0.4.17
/** * @dev Send ether to buy tokens during ICO * @dev or send less than 1 ether to contract to play * @dev or send 0 to collect prize */
function () payable external { if(msg.value > 0){ if(investStart>1){ // during ICO payment to the contract is treated as investment invest(owner); } else{ // if not ICO running payment to contract is treated as play play(); }...
0.4.17
/** * @dev Play in lottery with own numbers * @param _partner Affiliate partner */
function playSystem(uint _hash, address _partner) payable public returns (uint) { won(); // check if player did not win uint24 bethash = uint24(_hash); require(msg.value <= 1 ether && msg.value < hashBetMax); if(msg.value > 0){ if(investStart==0) { // dividends only aft...
0.4.17
/** * @dev Create hash data swap space * @param _sadd Number of hashes to add (<=256) */
function addHashes(uint _sadd) public returns (uint) { require(hashFirst == 0 && _sadd > 0 && _sadd <= hashesSize); uint n = hashes.length; if(n + _sadd > hashesSize){ hashes.length = hashesSize; } else{ hashes.length += _sadd; } f...
0.4.17
/** * @dev Fill hash data */
function putHash() public returns (bool) { uint lastb = hashLast; if(lastb == 0 || block.number <= lastb + 10) { return(false); } if(lastb < block.number - 245) { uint num = block.number - 245; lastb = num - (num % 10); } uint ...
0.4.17
/** * administrative to upload the names and images associated with each trait * @param traitType the trait type to upload the traits for (see traitTypes for a mapping) * @param traits the names and base64 encoded PNGs for each trait * @param traitIds the ids for traits */
function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner { require(traitIds.length == traits.length, "Mismatched inputs"); for (uint i = 0; i < traits.length; i++) { traitData[traitType][traitIds[i]] = Trait( traits[i].name...
0.8.4
/** * generates an entire SVG by composing multiple <image> elements of PNGs * @param tokenId the ID of the token to generate an SVG for * @return a valid SVG of the Cat / Mouse */
function drawSVG(uint256 tokenId) internal view returns (string memory) { IHouse.HouseStruct memory s = houseNFT.getTokenTraits(tokenId); uint8 shift = 0; if (s.roll == 0) { shift = 0; } else if (s.roll == 1) { shift = 1; } else { shift = 2; ...
0.8.4
/** * generates an array composed of all the individual traits and values * @param tokenId the ID of the token to compose the metadata for * @return a JSON array of all of the attributes for given token ID */
function compileAttributes(uint256 tokenId) internal view returns (string memory) { IHouse.HouseStruct memory s = houseNFT.getTokenTraits(tokenId); string memory traits; traits = string(abi.encodePacked( attributeForTypeAndValue(_traitTypes[0], traitData[s.roll][s.body].name), ',...
0.8.4
// Update Signatures
function updateSignatures(string[] calldata nftTokenIds, bytes32[] calldata _signatures) public onlyOwner { for (uint256 i=0; i < nftTokenIds.length; i++) { string memory nftTokenId = nftTokenIds[i]; bytes32 signature = _signatures[i]; signatures[nftTokenId] = signature; } }
0.8.7
// Claim Tokens
function claimTokens(uint _amount, string memory nftTokenId, string memory privateKey, bytes32 newSignature) public { require(claimTokensStatus, "Claiming tokens is not active at the moment."); auth(nftTokenId,privateKey,newSignature); require(_amount > 0, "You have to claim at least 1 token."); ui...
0.8.7
// Buy Tokens
function buyTokens(uint256 _amount) public payable returns (uint256 _amountBought) { require(buyTokensStatus, "Buying tokens is not active at the moment."); if (msg.sender != owner()) { require(msg.value > 0, "Send ETH to buy some tokens."); uint256 ethCost = costToBuy * _amount; require(m...
0.8.7
// Sell Tokens
function sellTokens(uint256 _amount) public { require(sellTokensStatus, "Selling tokens is not active at the moment."); require(_amount > 0, "Specify an amount of tokens greater than zero."); uint256 userBalance = ERC20(address(this)).balanceOf(msg.sender); require(userBalance >= _amount, "Your ...
0.8.7
// Send Tokens Back to Contract
function sendTokensBack(uint256 _amount) public { require(sendTokensBackStatus, "Sending tokens back is not active at the moment."); require(_amount > 0, "Specify an amount of tokens greater than zero."); uint256 userBalance = ERC20(address(this)).balanceOf(msg.sender); require(userBalance >= _a...
0.8.7
// Get Status
function getStatus(string memory _type) public view returns (bool _status) { if(compare(_type,"claimTokens")) { _status = claimTokensStatus; } else if(compare(_type,"buyTokens")) { _status = buyTokensStatus; } else if(compare(_type,"sellTokens")) { _status = sellTokensStatus; } else if(compare(_type,"sendTo...
0.8.7
// Set Status
function setStatus(string[] calldata _type, bool[] calldata _status) public onlyOwner { for (uint i=0; i < _type.length; i++) { if(compare(_type[i],"mint")) { mintStatus = _status[i]; } else if(compare(_type[i],"claimTokens")) { claimTokensStatus = _status[i]; } else if(compare(_type[i],"buyTokens")) ...
0.8.7
// Change Values for costToBuy and tokenSellValue and reserveAmount
function changeVars(string[] calldata _vars,uint256[] calldata _amounts) public onlyOwner { for (uint i=0; i < _vars.length; i++) { if(compare(_vars[i],"costToBuy")) { costToBuy = _amounts[i]; } else if(compare(_vars[i],"tokenSellValue")) { tokenSellValue = _amounts[i]; } else if(compare(_vars[i],"res...
0.8.7
// Withdraw Exact Amount
function withdrawAmount(uint256 _amount) public onlyOwner { uint256 ownerBalance = address(this).balance; require(ownerBalance >= _amount, "The contract does not have enough of a balance to withdraw."); (bool sent,) = msg.sender.call{value: _amount}(""); require(sent, "Failed to send withdraw.")...
0.8.7
// Withdraw
function withdraw() public onlyOwner { uint256 ownerBalance = address(this).balance; require(ownerBalance > 0, "The contract does not have a balance to withdraw."); (bool sent,) = msg.sender.call{value: address(this).balance}(""); require(sent, "Failed to send withdraw."); }
0.8.7
// Method for batch distribution of airdrop tokens.
function sendBatchCS(address[] _recipients, uint[] _values) external onlyOwner returns (bool) { require(_recipients.length == _values.length); uint senderBalance = _balances[msg.sender]; for (uint i = 0; i < _values.length; i++) { uint value = _values[i]; address to ...
0.4.24
// Method to check current ICO stage
function currentStage() public view returns (uint256) { require(now >=_startDates[0] && now <= _endDates[3]); if (now >= _startDates[0] && now <= _endDates[0]) return 0; if (now >= _startDates[1] && now <= _endDates[1]) return 1; if (now >= _startDates[2] && now <= _endDates[2]) return 2; if (n...
0.4.24
// Add address to Private Sale
function addtoPrivateSale(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner { addOfPrivateSale[_address] = true; emit EventPrivateSale(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercent, ...
0.4.24
// Add address to Contributors
function addtoContributos(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner { addOfContributors[_address] = true; emit EventContributors(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercent, ...
0.4.24
// Add address to Contributors2
function addtoContributos2(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner { addOfContributors2[_address] = true; emit EventContributors2(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercent...
0.4.24
// Add address to Tech & Operation
function addtoTechOperation(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner { addOfTechOperation[_address] = true; emit EventTechOperation(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercen...
0.4.24
// Add address to Marketing & Business Development
function addtoMarketingBusinessDev(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner { addOfMarketingBusinessDev[_address] = true; emit EventMarketingBusinessDev(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPer...
0.4.24
// Add address to Early Investors
function addtoEarlyInvestors(address _address, uint _transferPercent, uint _transferPercentTotal) public onlyOwner{ addOfEarlyInvestor[_address] = true; emit EventEarlyInvestor(_address, true); lockupHolderMap[_address] = LockupHolderDetails({ transferPercent: _transferPercen...
0.4.24
/** * @notice Redeem `dDaiToBurn` dDai from `msg.sender`, use the corresponding * cDai to redeem Dai, and transfer the Dai to `msg.sender`. * @param dDaiToBurn uint256 The amount of dDai to provide for Dai. * @return The amount of Dai received in return for the provided cDai. */
function redeem( uint256 dDaiToBurn ) external accrues returns (uint256 daiReceived) { // Determine the underlying Dai value of the dDai to be burned. daiReceived = dDaiToBurn.mul(_dDaiExchangeRate) / _SCALING_FACTOR; // Burn the dDai. _burn(msg.sender, daiReceived, dDaiToBurn); // ...
0.5.11
/** * @notice Redeem the dDai equivalent value of Dai amount `daiToReceive` from * `msg.sender`, use the corresponding cDai to redeem Dai, and transfer the * Dai to `msg.sender`. * @param daiToReceive uint256 The amount, denominated in Dai, of the cDai to * provide for Dai. * @return The amount of dDai burn...
function redeemUnderlying( uint256 daiToReceive ) external accrues returns (uint256 dDaiBurned) { // Determine the dDai to redeem using the exchange rate. dDaiBurned = daiToReceive.mul(_SCALING_FACTOR).div(_dDaiExchangeRate); // Burn the dDai. _burn(msg.sender, daiToReceive, dDaiBurned); ...
0.5.11
/** * @notice Transfer cDai in excess of the total dDai balance to a dedicated * "vault" account. * @return The amount of cDai transferred to the vault account. */
function pullSurplus() external accrues returns (uint256 cDaiSurplus) { // Determine the cDai surplus (difference between total dDai and total cDai) (, cDaiSurplus) = _getSurplus(); // Transfer the cDai to the vault and ensure that the operation succeeds. (bool ok, bytes memory data) = address(_CD...
0.5.11
/** * @notice Transfer dDai equal to `amount` Dai from `msg.sender` to = * `recipient`. * @param recipient address The account to transfer tokens to. * @param amount uint256 The amount of tokens to transfer. * @return A boolean indicating whether the transfer was successful. */
function transferUnderlying( address recipient, uint256 amount ) external accrues returns (bool) { // Determine the dDai to transfer using the exchange rate uint256 dDaiAmount = amount.mul(_SCALING_FACTOR).div(_dDaiExchangeRate); _transfer(msg.sender, recipient, dDaiAmount); return true; ...
0.5.11
/** * @notice View function to get the dDai balance of an account, denominated in * its Dai equivalent value. * @param account address The account to check the balance for. * @return The total Dai-equivalent cDai balance. */
function balanceOfUnderlying( address account ) external view returns (uint256 daiBalance) { // Get most recent dDai exchange rate by determining accrued interest (uint256 dDaiExchangeRate,,) = _getAccruedInterest(); // Convert account balance to Dai equivalent using the exchange rate daiB...
0.5.11
/** * @notice Internal view function to get the current cDai exchange rate. * @return The current cDai exchange rate, or amount of Dai that is redeemable * for each cDai (with 18 decimal places added to the returned exchange rate). */
function _getCurrentExchangeRate() internal view returns (uint256 exchangeRate) { uint256 storedExchangeRate = _CDAI.exchangeRateStored(); uint256 blockDelta = block.number.sub(_CDAI.accrualBlockNumber()); if (blockDelta == 0) return storedExchangeRate; exchangeRate = blockDelta == 0 ? storedExc...
0.5.11
/** * @notice Internal view function to get the total surplus, or cDai * balance that exceeds the total dDai balance. * @return The total surplus, denominated in both Dai and in cDai. */
function _getSurplus() internal view returns ( uint256 daiSurplus, uint256 cDaiSurplus ) { (uint256 dDaiExchangeRate, uint256 cDaiExchangeRate,) = _getAccruedInterest(); // Determine the total value of all issued dDai in Dai, rounded up uint256 dDaiUnderlying = ( _totalSupply.mul(dDaiExc...
0.5.11
/** * @notice Internal pure function to determine if a call to cDai succeeded and * to revert, supplying the reason, if it failed. Failure can be caused by a * call that reverts, or by a call that does not revert but returns a non-zero * error code. * @param functionSelector bytes4 The function selector that ...
function _checkCompoundInteraction( bytes4 functionSelector, bool ok, bytes memory data ) internal pure { // Determine if something went wrong with the attempt. if (ok) { uint256 compoundError = abi.decode(data, (uint256)); // throws on no data if (compoundError != _COMPOUND_SUCCESS) { ...
0.5.11
/** * @notice Internal pure function to get a Compound function name based on the * selector. * @param functionSelector bytes4 The function selector. * @return The name of the function as a string. */
function _getFunctionName( bytes4 functionSelector ) internal pure returns (string memory functionName) { if (functionSelector == _CDAI.mint.selector) { functionName = 'mint'; } else if (functionSelector == _CDAI.redeemUnderlying.selector) { functionName = 'redeemUnderlying'; } else...
0.5.11
/** * @notice Internal pure function to decode revert reasons. The revert reason * prefix is removed and the remaining string argument is decoded. * @param revertData bytes The raw data supplied alongside the revert. * @return The decoded revert reason string. */
function _decodeRevertReason( bytes memory revertData ) internal pure returns (string memory revertReason) { // Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector if ( revertData.length > 68 && // prefix (4) + position (32) + length (32) revertData[0] == byte(0x08)...
0.5.11
// ------------------------------------------------------------------------ // Token holders can stake their tokens using this function // @param tokens number of tokens to stake // ------------------------------------------------------------------------
function STAKE(uint256 tokens) external nonReentrant { require(IERC20(TRY).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from user for locking"); uint256 transferTxFee = (onePercent(tokens).mul(txFee)).div(10); uint256 tokensToStake = (token...
0.7.5
// ------------------------------------------------------------------------ // Private function to register payouts // ------------------------------------------------------------------------
function _addPayout(uint256 tokens_) private{ // divide the funds among the currently staked tokens // scale the deposit and add the previous remainder uint256 available = (tokens_.mul(scaling)).add(scaledRemainder); uint256 dividendPerToken = available.div(totalStakes); sc...
0.7.5
// ------------------------------------------------------------------------ // Stakers can claim their pending rewards using this function // ------------------------------------------------------------------------
function CLAIMREWARD() public nonReentrant{ if(totalDividends > stakers[msg.sender].fromTotalDividend){ uint256 owing = pendingReward(msg.sender); owing = owing.add(stakers[msg.sender].remainder); stakers[msg.sender].remainder = 0; ...
0.7.5
// ------------------------------------------------------------------------ // Get the pending rewards of the staker // @param _staker the address of the staker // ------------------------------------------------------------------------
function pendingReward(address staker) private returns (uint256) { require(staker != address(0), "ERC20: sending to the zero address"); uint stakersRound = stakers[staker].round; uint256 amount = ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).di...
0.7.5
// ------------------------------------------------------------------------ // Stakers can un stake the staked tokens using this function // @param tokens the number of tokens to withdraw // ------------------------------------------------------------------------
function WITHDRAW(uint256 tokens) external nonReentrant{ require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw"); totalStakes = totalStakes.sub(tokens); // add pending rewards to remainder to be claimed by user later, if there ...
0.7.5
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param masterCopy Address of master copy. /// @param data Payload for message call sent to new proxy contract.
function createProxy(address masterCopy, bytes memory data) public returns (Proxy proxy) { proxy = new Proxy(masterCopy); if (data.length > 0) // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, proxy, 0, ...
0.5.11
/// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer. /// This method is only meant as an utility to be called from other methods /// @param _mastercopy Address of master copy. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce N...
function deployProxyWithNonce(address _mastercopy, bytes memory initializer, uint256 saltNonce) internal returns (Proxy proxy) { // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it bytes32 salt = k...
0.5.11
/// @notice Migrate tokens to the new token contract. /// @dev Required state: Operational Migration /// @param _value The amount of token to be migrated
function migrate(uint256 _value) external { // Abort if not in Operational Migration state. if (funding) throw; if (migrationAgent == 0) throw; // Validate input value. if (_value == 0) throw; if (_value > balances[msg.sender]) throw; balances[msg.sende...
0.4.4
/// @notice Finalize crowdfunding /// @dev If cap was reached or crowdfunding has ended then: /// create GNT for the Golem Factory and developer, /// transfer ETH to the Golem Factory address. /// @dev Required state: Funding Success /// @dev State transition: -> Operational Normal
function finalize() external { // Abort if not in Funding Success state. if (!funding) throw; if ((block.number <= fundingEndBlock || totalTokens < tokenCreationMin) && totalTokens < tokenCreationCap) throw; // Switch to Operational state. This is the onl...
0.4.4
/// @notice Get back the ether sent during the funding in case the funding /// has not reached the minimum level. /// @dev Required state: Funding Failure
function refund() external { // Abort if not in Funding Failure state. if (!funding) throw; if (block.number <= fundingEndBlock) throw; if (totalTokens >= tokenCreationMin) throw; var gntValue = balances[msg.sender]; if (gntValue == 0) throw; balances[msg...
0.4.4
/// @notice Allow developer to unlock allocated tokens by transferring them /// from GNTAllocation to developer's address.
function unlock() external { if (now < unlockedAt) throw; // During first unlock attempt fetch total number of locked tokens. if (tokensCreated == 0) tokensCreated = gnt.balanceOf(this); var allocation = allocations[msg.sender]; allocations[msg.sender] = 0; ...
0.4.4
///@dev the main function to be executed ///@param _minReqBurnt REQ token needed to be burned. ///@param _deadline maximum timestamp to accept the trade from the router
function burn(uint _minReqBurnt, uint256 _deadline) external returns(uint) { IERC20 dai = IERC20(LOCKED_TOKEN_ADDRESS); IBurnableErc20 req = IBurnableErc20(BURNABLE_TOKEN_ADDRESS); uint daiToConvert = dai.balanceOf(address(this)); if (_deadline == 0) { ...
0.5.17
/** * @dev for mint function * @param account The address to get the reward. * @param amount The amount of the reward. */
function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); require(_whitelist[account] > 0, "must in whitelist"); _allGotBalances = _allGotBalances.add(amount); _gotBalances[account] = _gotBalanc...
0.5.5
/** * @dev Calculate and reuturn Unclaimed rewards */
function earned(address account) public view returns (uint256) { require(_whitelist[account] > 0, "must in whitelist"); uint256 reward = 0; uint256 accountTotal = _whitelist[account]; uint256 rewardPerSecond = accountTotal.mul(_rewardRate2).div(_baseRate).div(_rewardDurationTi...
0.5.5
// (base^exponent) % FIELD_SIZE // Cribbed from https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4
function bigModExp(uint256 base, uint256 exponent) internal view returns (uint256 exponentiation) { uint256 callResult; uint256[6] memory bigModExpContractInputs; bigModExpContractInputs[0] = WORD_LENGTH_BYTES; // Length of base bigModExpContractInputs[1] = WORD_LENGTH_BYTES; // Leng...
0.6.12
// Hash x uniformly into {0, ..., FIELD_SIZE-1}.
function fieldHash(bytes memory b) internal pure returns (uint256 x_) { x_ = uint256(keccak256(b)); // Rejecting if x >= FIELD_SIZE corresponds to step 2.1 in section 2.3.4 of // http://www.secg.org/sec1-v2.pdf , which is part of the definition of // string_to_point in the IETF draft...
0.6.12
// Hash b to a random point which hopefully lies on secp256k1.
function newCandidateSecp256k1Point(bytes memory b) internal view returns (uint256[2] memory p) { p[0] = fieldHash(b); p[1] = squareRoot(ySquared(p[0])); if (p[1] % 2 == 1) { p[1] = FIELD_SIZE - p[1]; } }
0.6.12
/** ********************************************************************* * @notice Check that product==scalar*multiplicand * * @dev Based on Vitalik Buterin's idea in ethresear.ch post cited below. * * @param multiplicand: secp256k1 point * @param scalar: non-zero GF(GROUP_ORDER) scalar * @param product:...
function ecmulVerify( uint256[2] memory multiplicand, uint256 scalar, uint256[2] memory product ) internal pure returns (bool verifies) { require(scalar != 0, "scalar must not be 0"); // Rules out an ecrecover failure case uint256 x = multiplicand[0]; // x ordinate of m...
0.6.12
// p1+p2, as affine points on secp256k1. // // invZ must be the inverse of the z returned by projectiveECAdd(p1, p2). // It is computed off-chain to save gas. // // p1 and p2 must be distinct, because projectiveECAdd doesn't handle // point doubling.
function affineECAdd( uint256[2] memory p1, uint256[2] memory p2, uint256 invZ ) internal pure returns (uint256[2] memory) { uint256 x; uint256 y; uint256 z; (x, y, z) = projectiveECAdd(p1[0], p1[1], p2[0], p2[1]); require(mulmod(z, invZ, FIEL...
0.6.12
// True iff address(c*p+s*g) == lcWitness, where g is generator. (With // cryptographically high probability.)
function verifyLinearCombinationWithGenerator( uint256 c, uint256[2] memory p, uint256 s, address lcWitness ) internal pure returns (bool) { // Rule out ecrecover failure modes which return address 0. require(lcWitness != address(0), "bad witness"); ui...
0.6.12
// c*p1 + s*p2. Requires cp1Witness=c*p1 and sp2Witness=s*p2. Also // requires cp1Witness != sp2Witness (which is fine for this application, // since it is cryptographically impossible for them to be equal. In the // (cryptographically impossible) case that a prover accidentally derives // a proof with equal c*p1 and s...
function linearCombination( uint256 c, uint256[2] memory p1, uint256[2] memory cp1Witness, uint256 s, uint256[2] memory p2, uint256[2] memory sp2Witness, uint256 zInv ) internal pure returns (uint256[2] memory) { require((cp1Witness[0] - sp2Wi...
0.6.12
// Pseudo-random number from inputs. // TODO(alx): We could save a bit of gas by following the standard here and // using the compressed representation of the points, if we collated the y // parities into a single bytes32. // https://www.pivotaltracker.com/story/show/171120588
function scalarFromCurvePoints( uint256[2] memory hash, uint256[2] memory pk, uint256[2] memory gamma, address uWitness, uint256[2] memory v ) internal pure returns (uint256 s) { return uint256( keccak256( abi....
0.6.12
// True if (gamma, c, s) is a correctly constructed randomness proof from pk // and seed. zInv must be the inverse of the third ordinate from // projectiveECAdd applied to cGammaWitness and sHashWitness. Corresponds to // section 5.3 of the IETF draft. // // TODO(alx): Since I'm only using pk in the ecrecover call, I c...
function verifyVORProof( uint256[2] memory pk, uint256[2] memory gamma, uint256 c, uint256 s, uint256 seed, address uWitness, uint256[2] memory cGammaWitness, uint256[2] memory sHashWitness, uint256 zInv ) internal view { req...
0.6.12
/* *************************************************************************** * @notice Returns proof's output, if proof is valid. Otherwise reverts * @param proof A binary-encoded proof * * Throws if proof is invalid, otherwise: * @return output i.e., the random output implied by the proof * **********...
function randomValueFromVORProof(bytes memory proof) internal view returns (uint256 output) { require(proof.length == PROOF_LENGTH, "wrong proof length"); uint256[2] memory pk; // parse proof contents into these variables uint256[2] memory gamma; // c, s and seed combined (prevents...
0.6.12
/** * @notice Commits calling address to serve randomness * @param _fee minimum xFUND payment required to serve randomness * @param _oracle the address of the node with the proving key * @param _publicProvingKey public key used to prove randomness */
function registerProvingKey( uint256 _fee, address payable _oracle, uint256[2] calldata _publicProvingKey ) external { bytes32 keyHash = hashOfKey(_publicProvingKey); address oldVOROracle = serviceAgreements[keyHash].vOROracle; require(oldVOROracle == address(0...
0.6.12
/** * @notice Changes the provider's base fee * @param _publicProvingKey public key used to prove randomness * @param _fee minimum xFUND payment required to serve randomness */
function changeFee(uint256[2] calldata _publicProvingKey, uint256 _fee) external { bytes32 keyHash = hashOfKey(_publicProvingKey); require(serviceAgreements[keyHash].vOROracle == _msgSender(), "only oracle can change the fee"); require(_fee > 0, "fee cannot be zero"); require(_fee <=...
0.6.12
/** * @notice Changes the provider's fee for a consumer contract * @param _publicProvingKey public key used to prove randomness * @param _fee minimum xFUND payment required to serve randomness */
function changeGranularFee(uint256[2] calldata _publicProvingKey, uint256 _fee, address _consumer) external { bytes32 keyHash = hashOfKey(_publicProvingKey); require(serviceAgreements[keyHash].vOROracle == _msgSender(), "only oracle can change the fee"); require(_fee > 0, "fee cannot be zero"...
0.6.12
/** * @notice creates the request for randomness * * @param _keyHash ID of the VOR public key against which to generate output * @param _consumerSeed Input to the VOR, from which randomness is generated * @param _feePaid Amount of xFUND sent with request. Must exceed fee for key * * @dev _consumerSeed is ...
function randomnessRequest( bytes32 _keyHash, uint256 _consumerSeed, uint256 _feePaid ) external sufficientXFUND(_feePaid, _keyHash) { require(address(_msgSender()).isContract(), "request can only be made by a contract"); xFUND.transferFrom(_msgSender(), address(this)...
0.6.12
/** * @notice Called by the node to fulfill requests * * @param _proof the proof of randomness. Actual random output built from this */
function fulfillRandomnessRequest(bytes memory _proof) public { (bytes32 currentKeyHash, Callback memory callback, bytes32 requestId, uint256 randomness) = getRandomnessFromProof(_proof); // Pay oracle address payable oracle = serviceAgreements[currentKeyHash].vOROracle; ...
0.6.12
/** * @dev Internal function to remove a token ID from the list of a given address * This function is internal due to language limitations, see the note in ERC721.sol. * It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event, * and doesn't clear approvals. * @pa...
function _removeTokenFrom(address from, uint256 tokenId) internal { super._removeTokenFrom(from, tokenId); // To prevent a gap in the array, we store the last token in the index of the token to delete, and // then delete the last slot. uint256 tokenIndex = _ownedTokensIndex[tokenId]; uint256 ...
0.4.25
/** * @dev Add Token Category for the tokenUri. * * @param _tokenUri string token URI of the category * @param _categoryId uint categoryid of the category * @param _maxQnty uint maximum quantity of tokens allowed to be minted * @param _price uint price tokens of that category will be sold at * @return T...
function addTokenCategory(string _tokenUri, CategoryId _categoryId, uint _maxQnty, uint _price) public onlyOwner returns (bool success) { // price should be more than MIN_PRICE require(_price >= MIN_PRICE); // can't override existing category require(tokenCategories[_tokenUri].price ==...
0.4.25
/** * @dev Checks that it's possible to buy gift and mint token with the tokenURI. * * @param _tokenUri string token URI of the category * @param _transitAddress address transit address assigned to gift * @param _value uint amount of ether, that is send in tx. * @return True if success. */
function canBuyGift(string _tokenUri, address _transitAddress, uint _value) public view whenNotPaused returns (bool) { // can not override existing gift require(gifts[_transitAddress].status == Statuses.Empty); // eth covers NFT price TokenCategory memory category = tokenCategories[_tokenUri]; ...
0.4.25
/** * @dev Buy gift and mint token with _tokenUri, new minted token will be kept in escrow * until receiver claims it. * * Received ether, splitted in 3 parts: * - 0.01 ETH goes to ephemeral account, so it can pay gas fee for claim transaction. * - token price (minus ephemeral account fee) goes to the...
function buyGift(string _tokenUri, address _transitAddress, string _msgHash) payable public whenNotPaused returns (bool) { require(canBuyGift(_tokenUri, _transitAddress, msg.value)); // get token price from the category for that token URI uint tokenPrice = tokenCategories[_tokenUri].pr...
0.4.25
/** * @dev Send donation to Giveth campaign * by calling function 'donateAndCreateGiver' of GivethBridge contract. * * @param _giver address giver address * @param _value uint donation amount (in wei) * @return True if success. */
function _makeDonation(address _giver, uint _value) internal returns (bool success) { bytes memory _data = abi.encodePacked(0x1870c10f, // function signature bytes32(_giver), bytes32(givethReceiverId), bytes32(0), bytes32(0)); // make donation tx success = givethBridge...
0.4.25
/** * @dev Get Gift assigned to transit address. * * @param _transitAddress address transit address assigned to gift * @return Gift details */
function getGift(address _transitAddress) public view returns ( uint256 tokenId, string tokenUri, address sender, // gift buyer uint claimEth, // eth for receiver uint nftPrice, // token price Statuses status, // gift status (deposited, claimed, cancelled) ...
0.4.25
/** * @dev Cancel gift and get sent ether back. Only gift buyer can * cancel. * * @param _transitAddress transit address assigned to gift * @return True if success. */
function cancelGift(address _transitAddress) public returns (bool success) { Gift storage gift = gifts[_transitAddress]; // is deposited and wasn't claimed or cancelled before require(gift.status == Statuses.Deposited); // only sender can cancel transfer; require(msg.sender == gift.send...
0.4.25
/** * @dev Claim gift to receiver's address if it is correctly signed * with private key for verification public key assigned to gift. * * @param _receiver address Signed address. * @return True if success. */
function claimGift(address _receiver) public whenNotPaused returns (bool success) { // only holder of ephemeral private key can claim gift address _transitAddress = msg.sender; Gift storage gift = gifts[_transitAddress]; // is deposited and wasn't claimed or cancelled before require(gif...
0.4.25
/// @dev Contract constructor sets owners, required number of confirmations, and recovery mode trigger. /// @param _owners List of owners. /// @param _required Number of required confirmations. /// @param _recoveryModeTriggerTime Time (in seconds) of inactivity before recovery mode is triggerable.
function MultiSigWallet(address[] _owners, uint _required, uint _recoveryModeTriggerTime) public { for (uint i=0; i<_owners.length; i++) { if (isOwner[_owners[i]] || _owners[i] == 0) revert(); isOwner[_owners[i]] = true; } owners = _own...
0.4.16
/// @dev Allows an owner to execute a confirmed transaction. /// @param transactionId Transaction ID.
function executeTransaction(uint transactionId) public ownerExists(msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; lastTransactionTime = ...
0.4.16
/** * @dev Set the fees in the system. All the fees are in mpip, except fixedTransferFee that is in wei. Level is between 0 and 2 */
function setFees(uint256 _dailyStorageFee, uint256 _fixedTransferFee, uint256 _dynamicTransferFee, uint256 _mintingFee, uint8 level) external onlyOwner { require(level<=2, "Level: Please use level 0 to 2."); dailyStorageFee[level] = _dailyStorageFee; fixedTransferFee[level] = _fixedTransferFe...
0.5.4
/* override the internal _transfer function so that we can take the fee, and conditionally do the swap + liquditiy */
function _transfer( address from, address to, uint256 amount ) internal override { // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquid...
0.6.12
/** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */
function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); abis[node][contentType] = data; emit ABIChanged(node, contentType); }
0.5.12
/** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */
function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) { mapping(uint256=>bytes) storage abiset = abis[node]; for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && abiset[contentTy...
0.5.12
/* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first bytes to compare. * @param offset Th...
function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) { uint shortest = len; if (otherlen < len) shortest = otherlen; uint selfptr; uint otherptr; assembly { selfp...
0.5.12
/* * @dev Returns the n byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes. * @param len The number of bytes. * @return The specified 32 bytes of the string. */
function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) { require(len <= 32); require(idx + len <= self.length); assembly { let mask := not(sub(exp(256, sub(32, len)), 1)) ret := and(mload(add(add(self, 32), idx)), mask) ...
0.5.12
/* * @dev Copies a substring into a new byte string. * @param self The byte string to copy from. * @param offset The offset to start copying at. * @param len The number of bytes to copy. */
function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) { require(offset + len <= self.length); bytes memory ret = new bytes(len); uint dest; uint src; assembly { dest := add(ret, 32) src := add(add(self,...
0.5.12
/** * @dev Returns the number of bytes in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The length of the DNS name at 'offset', in bytes. */
function nameLength(bytes memory self, uint offset) internal pure returns(uint) { uint idx = offset; while (true) { assert(idx < self.length); uint labelLen = self.readUint8(idx); idx += labelLen + 1; if (labelLen == 0) { break; ...
0.5.12
/** * @dev Moves the iterator to the next resource record. * @param iter The iterator to advance. */
function next(RRIterator memory iter) internal pure { iter.offset = iter.nextOffset; if (iter.offset >= iter.data.length) { return; } // Skip the name uint off = iter.offset + nameLength(iter.data, iter.offset); // Read type, class, and ttl ...
0.5.12
/** * @dev Checks if a given RR type exists in a type bitmap. * @param self The byte string to read the type bitmap from. * @param offset The offset to start reading at. * @param rrtype The RR type to check for. * @return True if the type is found in the bitmap, false otherwise. */
function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) { uint8 typeWindow = uint8(rrtype >> 8); uint8 windowByte = uint8((rrtype & 0xff) / 8); uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7))); for (uint off = offs...
0.5.12
/** * Set one or more DNS records. Records are supplied in wire-format. * Records with the same node/name/resource must be supplied one after the * other to ensure the data is updated correctly. For example, if the data * was supplied: * a.example.com IN A 1.2.3.4 * a.example.com IN A 5.6.7.8 * ...
function setDNSRecords(bytes32 node, bytes calldata data) external authorised(node) { uint16 resource = 0; uint256 offset = 0; bytes memory name; bytes memory value; bytes32 nameHash; // Iterate over the data to add the resource records for (RRUtils.RRItera...
0.5.12
/** * Returns the address of a contract that implements the specified interface for this name. * If an implementer has not been set for this interfaceID and name, the resolver will query * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that * contract implements EIP165 and ...
function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) { address implementer = interfaces[node][interfaceID]; if(implementer != address(0)) { return implementer; } address a = addr(node); if(a == address(0)) { ...
0.5.12
/** * @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update...
function updateAddressSetting( uint256 _settingId, address _newValue, address _proposalTAOId, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS, string memory _extraData) public canUpdate(_proposalTAOId) isAddressSetting(_settingId) { // Verify and store update address signa...
0.5.4
/** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _approved Whether to approve or reject */
function approveSettingUpdate(uint256 _settingId, bool _approved) public senderIsName senderNameNotCompromised { // Make sure setting exist require (_aoSetting.settingTypeLookup(_settingId) > 0); address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); (,,, address _proposalTAOId,,) = _...
0.5.4
/** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized */
function finalizeSettingUpdate(uint256 _settingId) public senderIsName senderNameNotCompromised { // Make sure setting exist require (_aoSetting.settingTypeLookup(_settingId) > 0); address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeUpdate(_se...
0.5.4
/** * @dev Verify the signature for the address update and store the signature info * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _v The V part ...
function _verifyAndStoreUpdateAddressSignature( uint256 _settingId, address _newValue, address _proposalTAOId, uint8 _v, bytes32 _r, bytes32 _s ) internal returns (bool) { bytes32 _hash = keccak256(abi.encodePacked(address(this), _settingId, _proposalTAOId, _newValue, _nameFactory.ethAddressToNa...
0.5.4
// This is an incredibly trustfull ENS deployment, only use for testing
function newENS(address _owner) public returns (ENS) { ENS ens = new ENS(); // Setup .eth TLD ens.setSubnodeOwner(ENS_ROOT, ETH_TLD_LABEL, this); // Setup public resolver PublicResolver resolver = new PublicResolver(ens); ens.setSubnodeOwner(ETH_TLD_NODE, PUBLIC...
0.4.24
/** * @dev Store the update hash lookup for this address setting * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _extraData Catch-all string value...
function _storeUpdateAddressHashLookup( uint256 _settingId, address _newValue, address _proposalTAOId, string memory _extraData) internal { // Store the update hash key lookup (address _addressValue,,,,) = _aoSettingValue.settingValue(_settingId); updateHashLookup[keccak256(abi.encodePacked(addr...
0.5.4