comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
// required return value from onERC721Received() function
function make( uint256 _sellunits, address _selltok, uint256 _askunits, address _asktok ) public payable returns (bytes32) { require( safelist[_selltok], "unrecognized sell token" ); require( safelist[_asktok], "unrecognized ask token" ); if (_sel...
0.6.10
// ERC721 (NFT) transfer callback
function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4) { if ( _operator == address(0x0) || _from == address(0x0) || _data.length > 0 )...
0.6.10
/// @notice registers wallet addresses for users /// @param users Array of strings that identifies users /// @param wallets Array of wallet addresses
function addWalletList(string[] memory users, address[] memory wallets) public onlyEndUserAdmin { require(users.length == wallets.length, "Whitelisted: User and wallet lists must be of same length!"); for (uint i = 0; i < wallets.length; i++) { _addWallet(users[i], wallets[i]); } ...
0.6.12
/// @notice returns current sell price for one token
function sellPrice() external view returns(uint256) { // avoid dividing by zero require(totalSupply != 0, "function called too early (supply is zero)"); //represents selling one "full token" since the token has 18 decimals uint256 etherValue = tokensToEther( 1e18 ); uint[2] mem...
0.5.12
/// @notice calculates current buy price for one token
function currentBuyPrice() external view returns(uint256) { // avoid dividing by zero require(totalSupply != 0, "function called too early (supply is zero)"); //represents buying one "full token" since the token has 18 decimals uint256 etherValue = tokensToEther( 1e18 ); uint[2...
0.5.12
/// @notice calculates amount of ether (as wei) received if input number of tokens is sold at current price and fee rate /// @param tokensToSell Desired number of tokens (as an integer) from which to calculate equivalent value of ether /// @return etherAfterFee Amount of ether that would be received for selling tokens
function calculateExpectedWei(uint256 tokensToSell) external view returns(uint256) { require( tokensToSell <= totalSupply, "unable to calculate for amount of tokens greater than current supply" ); //finds ether value of tokens before fee uint256 etherValue = tokensToEther( tokensToSell )...
0.5.12
/// @notice function for donating to slush fund. adjusts current fee rate as fast as possible but does not give the message sender any tokens /// @dev invoked internally when partner contract sends funds to this contract (see fallback function)
function makeItRain() public payable returns(bool) { //avoid dividing by zero require(totalSupply != 0, "makeItRain function called too early (supply is zero)"); uint256 amountEther = msg.value; uint256 addedRewards = SafeMath.mul( amountEther , MAGNITUDE ); uint256 additionalRe...
0.5.12
/// @notice returns reward balance of desired address /// @dev invoked internally in cashOut and doubleDown functions /// @param playerAddress Address which sender wants to know the rewards balance of /// @return playerRewards Current ether value of unspent rewards of playerAddress
function rewardsOf( address playerAddress ) public view returns(uint256 playerRewards) { playerRewards = (uint256) ( ( (int256)( _rewardsPerTokenAllTime * tokenBalanceLedger_[ playerAddress ] ) - payoutsToLedger_[ playerAddress ] ) / IMAGNITUDE ); return playerRewards; }
0.5.12
//INTERNAL FUNCTIONS //recalculates fee rate given current contract state
function calcFeeRate() internal returns(bool) { uint excessSlush = ( (_slushFundBalance % FEE_CYCLE_SIZE) * MAX_VARIANCE ); uint16 cycleLocation = uint16( excessSlush / FEE_CYCLE_SIZE ); uint16 newFeeRate = uint16( BASE_RATE + cycleLocation ); //copy local variable to state variable ...
0.5.12
//update rewards tracker when a user withdraws their rewards
function updateSpentRewards( address playerAddress, uint256 etherValue ) internal returns(bool) { int256 updatedPayouts = payoutsToLedger_[playerAddress] + int256 ( SafeMath.mul( etherValue, MAGNITUDE ) ); require( (updatedPayouts >= payoutsToLedger_[playerAddress]), "ERROR: integer overflow in upd...
0.5.12
//updates rewards tracker. makes sure that player does not receive any rewards accumulated before they purchased/received these tokens
function updateRewardsOnPurchase( address playerAddress, uint256 amountTokens ) internal returns(bool) { int256 updatedPayouts = payoutsToLedger_[playerAddress] + int256 ( SafeMath.mul( _rewardsPerTokenAllTime, amountTokens ) ); require( (updatedPayouts >= payoutsToLedger_[playerAddress]), "ERROR: ...
0.5.12
// PRIVILEGED FUNCTIONS // ====================
function releaseBatch() external onlyFounders { require(true == vestingStarted); require(now > nextPeriod); require(periodsPassed < totalPeriods); uint tokensToRelease = 0; do { periodsPassed = periodsPassed.add(1); nextPeriod = nextPeriod....
0.4.18
/** * @dev Constructs the allocator. * @param _icoBackend Wallet address that should be owned by the off-chain backend, from which \ * \ it mints the tokens for contributions accepted in other currencies. * @param _icoManager Allowed to start phase 2. * @param _foundersWallet Where the founders' toke...
function TokenAllocation(address _icoManager, address _icoBackend, address _foundersWallet, address _partnersWallet, address _emergencyManager ) public { require...
0.4.18
/** * @dev Issues the rewards for founders and early contributors. 18% and 12% of the total token supply by the end * of the crowdsale, respectively, including all the token bonuses on early contributions. Can only be * called after the end of the crowdsale phase, ends the current phase. */
function rewardFoundersAndPartners() external onlyManager onlyValidPhase onlyUnpaused { uint tokensDuringThisPhase; if (crowdsalePhase == CrowdsalePhase.PhaseOne) { tokensDuringThisPhase = totalTokenSupply; } else { tokensDuringThisPhase = totalTokenSupply - tokensDu...
0.4.18
//adds new tokens to total token supply and gives them to the player
function mint(address playerAddress, uint256 amountTokens) internal { require( playerAddress != address(0), "cannot mint tokens for zero address" ); totalSupply = SafeMath.add( totalSupply, amountTokens ); //updates rewards tracker. makes sure that player does not receive any rewards accumulated be...
0.5.12
/** * @dev Advance the bonus phase to next tier when appropriate, do nothing otherwise. */
function advanceBonusPhase() internal onlyValidPhase { if (crowdsalePhase == CrowdsalePhase.PhaseOne) { if (bonusPhase == BonusPhase.TenPercent) { bonusPhase = BonusPhase.FivePercent; } else if (bonusPhase == BonusPhase.FivePercent) { bonusPhase = Bon...
0.4.18
//Make sure you add the 9 zeros at the end!!!
function update_tiers(uint256 t1_size,uint256 t1_percent,uint256 t2_size,uint256 t2_percent,uint256 t3_size,uint256 t3_percent,uint256 t4_size,uint256 t4_percent,uint256 t5_size,uint256 t5_percent)external onlyOwner(){ tier1_size = t1_size; tier1_amount = t1_percent; tier2_size = t2_size; ti...
0.8.10
/** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); fo...
0.8.1
//update rewards tracker. makes sure that player can still withdraw rewards that accumulated while they were holding their sold/transferred tokens
function updateRewardsOnSale( address playerAddress, uint256 amountTokens ) internal returns(bool) { int256 updatedPayouts = payoutsToLedger_[playerAddress] - int256 ( SafeMath.mul( _rewardsPerTokenAllTime, amountTokens ) ); require( (updatedPayouts <= payoutsToLedger_[playerAddress]), "ERROR: inte...
0.5.12
//destroys sold tokens (removes sold tokens from total token supply) and subtracts them from player balance
function burn(address playerAddress, uint256 amountTokens) internal { require( playerAddress != address(0), "cannot burn tokens for zero address" ); require( amountTokens <= tokenBalanceLedger_[ playerAddress ], "insufficient funds available" ); //subtract tokens from player balance. performed firs...
0.5.12
//sells desired amount of tokens for ether
function sell(uint256 amountTokens) internal returns (bool) { require( amountTokens <= tokenBalanceLedger_[ msg.sender ], "insufficient funds available" ); //calculates fee and net value to send to seller uint256 etherValue = tokensToEther( amountTokens ); uint[2] memory feeAndValue = val...
0.5.12
//takes in amount and returns fee to pay on it and the value after the fee //classified as view since needs to access state (to pull current fee rate) but not write to it
function valueAfterFee( uint amount ) internal view returns (uint[2] memory outArray_ ) { outArray_[0] = SafeMath.div( SafeMath.mul(amount, _feeRate), 65536 ); //fee outArray_[1] = SafeMath.sub( amount , outArray_[0] ); //value after fee return outArray_; }
0.5.12
//returns purchased number of tokens based on linear bonding curve with fee //it's the quadratic formula stupid!
function etherToTokens(uint256 etherValue) internal view returns(uint256) { uint256 tokenPriceInitial = TOKEN_PRICE_INITIAL * 1e18; uint256 _tokensReceived = ( ( // avoids underflow SafeMath.sub( ( sqrt( ( tok...
0.5.12
//returns sell value of tokens based on linear bonding curve with fee //~inverse of etherToTokens, but with rounding down to ensure contract is always more than solvent
function tokensToEther(uint256 inputTokens) internal view returns(uint256) { uint256 tokens = ( inputTokens + 1e18 ); uint256 functionTotalSupply = ( totalSupply + 1e18 ); uint256 etherReceived = ( // avoids underflow SafeMath.sub( ( ( ( TOK...
0.5.12
/** * @notice Used for calculating the option price (the premium) and using * the swap router (if needed) to convert the tokens with which the user * pays the premium into the token in which the pool is denominated. * @param period The option period * @param amount The option size * @param strike The option strik...
function getOptionPrice( IHegicPool pool, uint256 period, uint256 amount, uint256 strike, address[] calldata swappath ) public view returns ( uint256 total, uint256 baseTotal, uint256 settlementFee, uint2...
0.8.6
/** * @notice Used for calculating the option price (the premium) * in the token in which the pool is denominated. * @param period The option period * @param amount The option size * @param strike The option strike **/
function getBaseOptionCost( IHegicPool pool, uint256 period, uint256 amount, uint256 strike ) public view returns ( uint256 total, uint256 settlementFee, uint256 premium ) { (settlementFee, premium) = poo...
0.8.6
/** * @notice Used for buying the option contract and converting * the buyer's tokens (the total premium) into the token * in which the pool is denominated. * @param period The option period * @param amount The option size * @param strike The option strike * @param acceptablePrice The highest acceptable price *...
function createOption( IHegicPool pool, uint256 period, uint256 amount, uint256 strike, address[] calldata swappath, uint256 acceptablePrice ) external payable { address buyer = _msgSender(); (uint256 optionPrice, uint256 rawOptionPrice, , ) = ...
0.8.6
/** * @dev Burns tokens from a specific address. * To burn the tokens the caller needs to provide a signature * proving that the caller is authorized by the token owner to do so. * @param db Token storage to operate on. * @param from The address holding tokens. * @param amount The amount of tokens to burn. ...
function burn( TokenStorage db, address from, uint amount, bytes32 h, uint8 v, bytes32 r, bytes32 s ) external returns (bool) { require( ecrecover(h, v, r, s) == from, "signature/hash does not m...
0.4.24
/** * @dev Transfers tokens from a specific address [ERC20]. * The address owner has to approve the spender beforehand. * @param db Token storage to operate on. * @param caller Address of the caller passed through the frontend. * @param from Address to debet the tokens from. * @param to Recipient address. ...
function transferFrom( TokenStorage db, address caller, address from, address to, uint amount ) external returns (bool success) { uint allowance = db.getAllowed(from, caller); db.subBalance(from, amount); db.addBalance(t...
0.4.24
/** * @dev Transfers tokens and subsequently calls a method on the recipient [ERC677]. * If the recipient is a non-contract address this method behaves just like transfer. * @notice db.transfer either returns true or reverts. * @param db Token storage to operate on. * @param caller Address of the caller passe...
function transferAndCall( TokenStorage db, address caller, address to, uint256 amount, bytes data ) external returns (bool) { require( db.transfer(caller, to, amount), "unable to transfer" ); i...
0.4.24
/** * @dev Recovers tokens from an address and reissues them to another address. * In case a user loses its private key the tokens can be recovered by burning * the tokens from that address and reissuing to a new address. * To recover tokens the contract owner needs to provide a signature * proving that the t...
function recover( TokenStorage token, address from, address to, bytes32 h, uint8 v, bytes32 r, bytes32 s ) external returns (uint) { require( ecrecover(h, v, r, s) == from, "signature/hash does ...
0.4.24
/** * @dev Prevents tokens to be sent to well known blackholes by throwing on known blackholes. * @param to The address of the intended recipient. */
function avoidBlackholes(address to) internal view { require(to != 0x0, "must not send to 0x0"); require(to != address(this), "must not send to controller"); require(to != address(token), "must not send to token storage"); require(to != frontend, "must not send to frontend"); }
0.4.24
/** * @dev initialize * @param _avatar the avatar to mint reputation from * @param _tokenContract the token contract * @param _agreementHash is a hash of agreement required to be added to the TX by participants */
function initialize(Avatar _avatar, IERC20 _tokenContract, CurveInterface _curve, bytes32 _agreementHash) external { require(avatar == Avatar(0), "can be called only one time"); require(_avatar != Avatar(0), "avatar cannot be zero"); tokenContract = _tokenContract; avatar = _ava...
0.5.13
/** * @dev redeemWithSignature function * @param _beneficiary the beneficiary address to redeem for * @param _signatureType signature type 1 - for web3.eth.sign 2 - for eth_signTypedData according to EIP #712. * @param _signature - signed data by the staker * @return uint256 minted reputation */
function redeemWithSignature( address _beneficiary, bytes32 _agreementHash, uint256 _signatureType, bytes calldata _signature ) external returns(uint256) { // Recreate the digest the user signed bytes32 delegationDigest; ...
0.5.13
/** * @dev redeem function * @param _beneficiary the beneficiary address to redeem for * @param _redeemer the redeemer address * @return uint256 minted reputation */
function _redeem(address _beneficiary, address _redeemer, bytes32 _agreementHash) private onlyAgree(_agreementHash) returns(uint256) { require(avatar != Avatar(0), "should initialize first"); require(redeems[_redeemer] == false, "redeeming twice from the same account is not allowed"); ...
0.5.13
/** * @dev Sets a new controller. * @param address_ Address of the controller. */
function setController(address address_) external onlyOwner { require(address_ != 0x0, "controller address cannot be the null address"); emit Controller(ticker, controller, address_); controller = SmartController(address_); require(controller.getFrontend() == address(this), "controll...
0.4.24
/** * @dev Burns tokens from token owner. * This removfes the burned tokens from circulation. * @param from Address of the token owner. * @param amount Number of tokens to burn. * @param h Hash which the token owner signed. * @param v Signature component. * @param r Signature component. * @param s Sigat...
function burnFrom(address from, uint amount, bytes32 h, uint8 v, bytes32 r, bytes32 s) external returns (bool ok) { ok = controller.burnFrom_withCaller(msg.sender, from, amount, h, v, r, s); emit Transfer(from, 0x0, amount); }
0.4.24
/** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */
function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( ...
0.8.4
/** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */
function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory curr...
0.8.4
/** * @dev Returns the current cost of minting. */
function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply ...
0.8.4
/** * @dev Returns the current ETH price to mint */
function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; ...
0.8.4
/** * @dev Mints new tokens. */
function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp ...
0.8.4
/** * @dev Hash to SVG function */
function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_...
0.8.4
/** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */
function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "...
0.8.4
/** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */
function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { ...
0.8.4
/** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */
function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIn...
0.8.4
/// @notice The `escapeHatch()` should only be called as a last resort if a /// security issue is uncovered or something unexpected happened /// @param _token to transfer, use 0x0 for ether
function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner { require(escapeBlacklist[_token]==false); uint256 balance; /// @dev Logic for ether if (_token == 0x0) { balance = this.balance; escapeHatchDestination.transfer(balance); ...
0.4.18
// set a token upgrader
function setTokenUpgrader(address _newToken) external onlyUpgradeMaster notInUpgradingState { require(canUpgrade()); require(_newToken != address(0)); tokenUpgrader = TokenUpgrader(_newToken); // Handle bad interface require(tokenUpgrader....
0.5.0
// Deposits underlying assets from the user into the vault contract
function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); ...
0.6.12
// Purchase a multiplier tier for the user
function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tier...
0.6.12
// only for burn after sale
function burnaftersale(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burne...
0.4.19
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
function Ownable() { /** * ownerManualMinter contains the eth address of the party allowed to manually mint outside the crowdsale contract * this is setup at construction time */ ownerManualMinter = 0x163dE8a97f6B338bb498145536d1178e1A42AF85 ; // To be changed right after contract is deploy...
0.4.18
// ERC721 gas limits how much fun we can have // mint (almost) any number junks
function fuck(uint _numFucks) public payable { // NOTE: DON'T use totalSupply() because they are BURNABLE require( areWeFucking == true, "TOO EARLY. sale hasn't started." ); require( _tokenIdTracker.current() < ARBITRARY_QUANTITY, "TOO LATE...
0.8.2
// calculate how much the cost for a number of junks, across the bondage curve
function howMuchBondage(uint _hits) public view returns (uint) { require( _tokenIdTracker.current()+_hits < ARBITRARY_QUANTITY, "TOO MANY. there aren't this many junks left." ); uint _cost; uint _index; for (_index; _index < _hits; _index++) { ...
0.8.2
// lists the junks owned by the address
function exposeJunk(address _owner) external view returns(uint[] memory) { uint junks = balanceOf(_owner); if (junks == 0) { return new uint[](0); } else { uint[] memory result = new uint[](junks); for (uint i = 0; i < junks; i++) { result[i] =...
0.8.2
// special, reserved for devs
function wank(uint _numWanks) public onlyOwner { require( areWeFucking == false, "TOO LATE. this should happen first." ); // how many we're keeping uint maxWanks = ARBITRARY_QUANTITY - SEXY*25 - MEME*4 - MUCH*6; // 595 uint latestId = _tokenIdTrac...
0.8.2
// Send additional tokens for new rate + Update rate for individual tokens
function updateRewardAmount(address stakingToken, uint256 newRate) public onlyOwner { require(block.timestamp >= stakingRewardsGenesis, 'StakingRewardsFactory::notifyRewardAmount: not ready'); StakingRewardsInfo storage info = stakingRewardsInfoByStakingToken[stakingToken]; require(info.sta...
0.5.17
/** * @notice Lets the manager create a wallet for an owner account. * The wallet is initialised with the version manager module, a version number and a first guardian. * The wallet is created using the CREATE opcode. * @param _owner The account address. * @param _versionManager The version manager module * @para...
function createWallet( address _owner, address _versionManager, address _guardian, uint256 _version ) external onlyManager { validateInputs(_owner, _versionManager, _guardian, _version); Proxy proxy = new Proxy(walletImplementation); addres...
0.6.12
/** * @notice Gets the address of a counterfactual wallet with a first default guardian. * @param _owner The account address. * @param _versionManager The version manager module * @param _guardian The guardian address. * @param _salt The salt. * @param _version The version of feature bundle. * @return _wallet Th...
function getAddressForCounterfactualWallet( address _owner, address _versionManager, address _guardian, bytes32 _salt, uint256 _version ) external view returns (address _wallet) { validateInputs(_owner, _versionManager, _guardian, _version)...
0.6.12
/** * @notice Helper method to configure a wallet for a set of input parameters. * @param _wallet The target wallet * @param _owner The account address. * @param _versionManager The version manager module * @param _guardian The guardian address. * @param _version The version of the feature bundle. */
function configureWallet( BaseWallet _wallet, address _owner, address _versionManager, address _guardian, uint256 _version ) internal { // add the factory to modules so it can add a guardian and upgrade the wallet to the required version address[] ...
0.6.12
/** * @notice Throws if the owner, guardian, version or version manager is invalid. * @param _owner The owner address. * @param _versionManager The version manager module * @param _guardian The guardian address * @param _version The version of feature bundle */
function validateInputs(address _owner, address _versionManager, address _guardian, uint256 _version) internal view { require(_owner != address(0), "WF: owner cannot be null"); require(IModuleRegistry(moduleRegistry).isRegisteredModule(_versionManager), "WF: invalid _versionManager"); require(_g...
0.6.12
/* * get balance */
function getBalance(address _tokenAddress) onlyOwner public { address _receiverAddress = getReceiverAddress(); if (_tokenAddress == address(0)) { require(_receiverAddress.send(address(this).balance)); return; } StandardToken token = StandardToken(_tokenAddre...
0.4.26
/// @notice Buy tokens from contract by sending ether
function buy() payable public { require(onSale); uint256 price = getPrice(); uint amount = msg.value * TOKENS_PER_DOLLAR * 10 ** uint256(decimals) / price; // calculates the amount require(balanceOf[owner] - amount >= storageAmount); ...
0.4.24
/** * @dev Returns true if `account` is a contract. * */
function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` ...
0.6.6
/** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `tr...
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.6
/** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */
function sendMessage( address _target, bytes memory _message, uint32 _gasLimit ) override public { bytes memory xDomainCalldata = _getXDomainCalldata( _target, msg.sender, _message, messageNonce ); m...
0.7.6
/** * @notice Verifies a proof that a given key/value pair is present in the * Merkle trie. * @param _key Key of the node to search for, as a hex string. * @param _value Value of the node to search for, as a hex string. * @param _proof Merkle trie inclusion proof for the desired node. Unlike * traditional Merkle ...
function verifyInclusionProof( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _verified ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.verifyI...
0.7.6
/** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. */
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _total...
0.6.6
/** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * */
function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _...
0.6.6
/** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. */
function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, ...
0.6.6
// multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); }
0.6.6
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2P...
0.6.6
/** * @notice Updates a Merkle trie and returns a new root hash. * @param _key Key of the node to update, as a hex string. * @param _value Value of the node to update, as a hex string. * @param _proof Merkle trie inclusion proof for the node *nearest* the * target node. If the key exists, we can simply update the ...
function update( bytes memory _key, bytes memory _value, bytes memory _proof, bytes32 _root ) internal pure returns ( bytes32 _updatedRoot ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.update(key, _va...
0.7.6
/** * @notice Retrieves the value associated with a given key. * @param _key Key to search for, as hex bytes. * @param _proof Merkle trie inclusion proof for the key. * @param _root Known root of the Merkle trie. * @return _exists Whether or not the key exists. * @return _value Value of the key if it exists. */
function get( bytes memory _key, bytes memory _proof, bytes32 _root ) internal pure returns ( bool _exists, bytes memory _value ) { bytes memory key = _getSecureKey(_key); return Lib_MerkleTrie.get(key, _proof, _root...
0.7.6
//Read Functions
function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } ...
0.8.0
/** * @dev Mint tokens through pre or public sale */
function mint() external payable { require(block.timestamp >= publicSaleTimestamp, "Public sale not live"); require(msg.value == cost, "Incorrect funds supplied"); // mint cost require(v1HomeTotal + 1 <= maxSupply, "All tokens have been minted"); require(balance...
0.8.9
/** * @dev Returns tokenURI, which, if revealedStatus = true, is comprised of the baseURI concatenated with the tokenId */
function tokenURI(uint256 _tokenId) public view override returns(string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); if (bytes(tokenURImap[_tokenId]).length == 0) { return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId))); ...
0.8.9
/** * @dev Airdrop 1 token to each address in array '_to' * @param _to - array of address' that tokens will be sent to */
function airDrop(address[] calldata _to) external onlyOwner { require(totalSupply() + _to.length <= maxSupply, "Minting this many would exceed total supply"); for (uint i=0; i<_to.length; i++) { uint tokenId = totalSupply() + 1; _mint(_to[i], tokenId); emit T...
0.8.9
/** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */
function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!pau...
0.8.4
/** * @dev See {ERC1155-_beforeTokenTransfer}. */
function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == ...
0.8.4
// withdrawal of funds on any and all stale bids that have been bested
function withdraw(address payable destination) public { uint256 amount = pendingWithdrawals[msg.sender]; require(amount > 0, "EtheriaEx: no amount to withdraw"); // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[destination] =...
0.8.3
// transferes from account 1 [@param1] to account 2 [@param 2] the designated amount [@param 3] // requires the person calling the function has at least the amount of the transfer authorized for them to send
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance...
0.8.0
// the person calling this function DECREASED the allowance of the address called [@param1] can spend // on their belave by the amount send [@param2]
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); uint256 newAllowance = currentAllowance....
0.8.0
// no need to check for balance here, _transfer function checks to see if the amount // being transfered is >= to the balance of the person sending the tokens
function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner...
0.8.0
// force Swap back if slippage above 49% for launch.
function forceSwapBack() external onlyOwner { uint256 contractBalance = balanceOf(address(this)); require(contractBalance >= totalSupply() / 100, "Can only swap back if more than 1% of tokens stuck on contract"); swapBack(); emit OwnerForcedSwapBack(block.timestamp); }
0.8.9
/** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */
function remove(Set storage self, address key) internal { require(exists(self, key), "AddressSet: key does not exist in the set."); uint last = count(self) - 1; uint rowToReplace = self.keyPointers[key]; if(rowToReplace != last) { address keyToMove = self.keyList[last]; ...
0.6.6
// Returns the id list of all active events
function getActiveEvents() external view returns(uint256[] memory) { StakingEvent[] memory _events = getAllEvents(); uint256 nbActive = 0; for (uint256 i = 0; i < _events.length; i++) { if (_events[i].blockEventClose >= block.number) { nbActive++; ...
0.6.6
// Returns the id list of all closed events
function getClosedEvents() external view returns(uint256[] memory) { StakingEvent[] memory _events = getAllEvents(); uint256 nbCompleted = 0; for (uint256 i = 0; i < _events.length; i++) { if (_events[i].blockEventClose < block.number) { nbCompleted++; ...
0.6.6
// Returns the % progress of the user towards completion of the event (100% = 1e5)
function getUserProgress(address _user, uint256 _eventId) external view returns(uint256) { StakingEvent memory _event = stakingEvents[_eventId]; UserInfo memory _userInfo = userInfo[_user][_eventId]; if (_userInfo.blockEnd == 0) { return 0; } if (_userInfo.i...
0.6.6
/************************************************************************************** * 1:1 Convertability to HODLT ERC20 **************************************************************************************/
function hodlTIssue(uint amount) external distribute accrueByTime ifRunning { User storage u = userStruct[msg.sender]; User storage t = userStruct[address(token)]; u.balanceHodl = u.balanceHodl.sub(amount); t.balanceHodl = t.balanceHodl.add(amount); _pruneHodler(msg.sender);...
0.6.6
/************************************************************************************** * Sell HodlC to buy orders, or if no buy orders open a sell order. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) and return unprocessed Hodl. **************************...
function sellHodlC(uint quantityHodl, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit SellHodlC(msg.sender, quantityHodl, lowGas); uint orderUsd = convertHodlToUsd(quantityHodl); uint orderLimit = orderLimit(); require(orderUsd >= minOrderUsd,...
0.6.6
/************************************************************************************** * Buy HodlC from sell orders, or if no sell orders, from reserve. Lastly, open a * buy order is the reserve is sold out. * Selectable low gas protects against future EVM price changes. * Completes as much as possible (gas) ...
function buyHodlC(uint amountEth, uint lowGas) external accrueByTime distribute ifRunning returns(bytes32 orderId) { emit BuyHodlC(msg.sender, amountEth, lowGas); uint orderLimit = orderLimit(); uint orderUsd = convertEthToUsd(amountEth); require(orderUsd >= minOrderUsd, "Bu...
0.6.6
/************************************************************************************** * Cancel orders **************************************************************************************/
function cancelSell(bytes32 orderId) external accrueByTime distribute ifRunning { SellOrder storage o = sellOrder[orderId]; User storage u = userStruct[o.seller]; require(o.seller == msg.sender, "Sender is not the seller."); u.balanceHodl = u.balanceHodl.add(o.volumeHodl); u...
0.6.6
// Moves forward in 1-day steps to prevent overflow
function rates() public view returns(uint hodlUsd, uint dailyAccrualRate) { hodlUsd = HODL_USD; dailyAccrualRate = DAILY_ACCRUAL_RATE; uint startTime = BIRTHDAY.add(SLEEP_TIME); if(now > startTime) { uint daysFromStart = (now.sub(startTime)) / 1 days; uint d...
0.6.6
/************************************************************************************** * Initialization functions that support migration cannot be used after trading starts **************************************************************************************/
function initUser(address userAddr, uint hodl) external onlyOwner payable { User storage u = userStruct[userAddr]; User storage r = userStruct[address(this)]; u.balanceEth = u.balanceEth.add(msg.value); u.balanceHodl = u.balanceHodl.add(hodl); r.balanceHodl = r.balanceHodl....
0.6.6
/** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */
function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatac...
0.6.12
// Create a new staking event
function createStakingEvent(uint256[] memory _cardIdList, uint256 _cardAmountAny, uint256[] memory _cardAmountList, uint256 _cardRewardId, uint256 _blockStakeLength, uint256 _blockEventClose, uint256[] memory _toBurnIdList, uint256[] memory _toBurnAmountList) public onlyOwner { require(_cardIdList.l...
0.6.6
// Stake cards into a staking event
function stakeAny(uint256 _eventId, uint256[] memory _cardIdList, uint256[] memory _cardAmountList) public { require(_cardIdList.length == _cardAmountList.length, "Arrays have different length"); StakingEvent storage _event = stakingEvents[_eventId]; UserInfo storage _userInfo = userInfo[ms...
0.6.6
// Add a new token to the pool. Can only be called by the owner.
function add( uint256 _allocPoint, IERC20 _token, bool _withUpdate ) external onlyOwner { require(!isTokenAdded(_token), "add: token already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > star...
0.7.6
// claim rewards
function claim() external{ uint256 i; for (i = 0; i < poolInfo.length; ++i) { updatePool(i); accrueReward(i); UserPoolInfo storage userPool = userPoolInfo[i][msg.sender]; userPool.accruedReward = calcReward(poolInfo[i], userPool); } uint256...
0.7.6