comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/* * Function to get token URI of given token ID */
function uri( uint256 _tokenId ) public view virtual override returns (string memory) { require(_tokenId<totalSupply, "ERC1155Metadata: URI query for nonexistent token"); if (!reveal) { return string(abi.encodePacked(bl...
0.8.4
/** * @notice Check to see whether the two stakers are in the same challenge * @param stakerAddress1 Address of the first staker * @param stakerAddress2 Address of the second staker * @return Address of the challenge that the two stakers are in */
function inChallenge(address stakerAddress1, address stakerAddress2) internal view returns (address) { Staker storage staker1 = _stakerMap[stakerAddress1]; Staker storage staker2 = _stakerMap[stakerAddress2]; address challenge = staker1.currentChallenge; requi...
0.6.11
/** * @notice Reduce the stake of the given staker to the given target * @param stakerAddress Address of the staker to reduce the stake of * @param target Amount of stake to leave with the staker * @return Amount of value released from the stake */
function reduceStakeTo(address stakerAddress, uint256 target) internal returns (uint256) { Staker storage staker = _stakerMap[stakerAddress]; uint256 current = staker.amountStaked; require(target <= current, "TOO_LITTLE_STAKE"); uint256 amountWithdrawn = current.sub(target); stak...
0.6.11
/** * @notice Advance the given staker to the given node * @param stakerAddress Address of the staker adding their stake * @param nodeNum Index of the node to stake on */
function stakeOnNode( address stakerAddress, uint256 nodeNum, uint256 confirmPeriodBlocks ) internal { Staker storage staker = _stakerMap[stakerAddress]; INode node = _nodes[nodeNum]; uint256 newStakerCount = node.addStaker(stakerAddress); staker.latestStakedN...
0.6.11
/// @dev Deposits funds from the caller into the vault. /// /// @param _amount the amount of funds to deposit.
function deposit(Data storage _self, uint256 _amount) internal returns (uint256) { // Push the token that the vault accepts onto the stack to save gas. IDetailedERC20 _token = _self.token(); _token.safeTransfer(address(_self.adapter), _amount); _self.adapter.deposit(_amount); _self.totalDepos...
0.6.12
/// @dev Directly withdraw deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. /// @param _amount the amount of tokens to withdraw.
function directWithdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) { IDetailedERC20 _token = _self.token(); uint256 _startingBalance = _token.balanceOf(_recipient); uint256 _startingTotalValue = _self.totalValue(); _self.adapter.withdraw(_recipie...
0.6.12
/// The rich get richer, the whale get whaler
function () payable{ if (block.number - period >= blockheight){ // time is over, Matthew won bool isSuccess=false; //mutex against recursion attack var nextStake = this.balance * WINNERTAX_PRECENT/100; // leave some money for the next round if (isSuccess == false) ...
0.4.7
/** * @dev Initializes balances on token launch. * @param accounts The addresses to mint to. * @param amounts The amounts to be minted. */
function initBalances(address[] calldata accounts, uint32[] calldata amounts) external onlyOwner returns (bool) { require(!_balancesInitialized, "Balance initialization already complete."); require(accounts.length > 0 && accounts.length == amounts.length, "Mismatch between number of accounts and amoun...
0.5.16
// Note that owners_ must be strictly increasing, in order to prevent duplicates
function createWallet(bytes32 id, address owner) internal { Wallet storage wallet = wallets[id]; require(wallet.owner == address(0), "Wallet already exists"); wallet.owner = owner; wallet.DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712DOMAINTYPE_HASH, ...
0.5.8
/// @dev singleTransferERC20 sends tokens from contract. /// @param _destToken The address of target token. /// @param _to The address of recipient. /// @param _amount The amount of tokens. /// @param _totalSwapped The amount of swap. /// @param _rewardsAmount The fees that should be paid. /// @param _redeemedFloatTxId...
function singleTransferERC20( address _destToken, address _to, uint256 _amount, uint256 _totalSwapped, uint256 _rewardsAmount, bytes32[] memory _redeemedFloatTxIds ) external override onlyOwner returns (bool) { require(whitelist[_destToken], "_destToke...
0.7.5
/// @dev multiTransferERC20TightlyPacked sends tokens from contract. /// @param _destToken The address of target token. /// @param _addressesAndAmounts The address of recipient and amount. /// @param _totalSwapped The amount of swap. /// @param _rewardsAmount The fees that should be paid. /// @param _redeemedFloatTxIds...
function multiTransferERC20TightlyPacked( address _destToken, bytes32[] memory _addressesAndAmounts, uint256 _totalSwapped, uint256 _rewardsAmount, bytes32[] memory _redeemedFloatTxIds ) external override onlyOwner returns (bool) { require(whitelist[_destToken]...
0.7.5
/** @notice send epoch reward to staking contract */
function distribute() external returns ( bool ) { if ( nextEpochTime <= uint32(block.timestamp) ) { nextEpochTime = nextEpochTime.add32( epochLength ); // set next epoch time // distribute rewards to each recipient for ( uint i = 0; i < info.length; i++ ) { ...
0.7.5
/** @notice increment reward rate for collector */
function adjust( uint _index ) internal { Adjust memory adjustment = adjustments[ _index ]; if ( adjustment.rate != 0 ) { if ( adjustment.add ) { // if rate should increase info[ _index ].rate = info[ _index ].rate.add( adjustment.rate ); // raise rate if...
0.7.5
/** @notice view function for next reward for specified address @param _recipient address @return uint */
function nextRewardFor( address _recipient ) public view returns ( uint ) { uint reward; for ( uint i = 0; i < info.length; i++ ) { if ( info[ i ].recipient == _recipient ) { reward = nextRewardAt( info[ i ].rate ); } } return reward; }
0.7.5
/// @dev Transfers a token and returns if it was a success /// @param token Token that should be transferred /// @param receiver Receiver to whom the token should be transferred /// @param amount The amount of tokens that should be transferred
function transferToken ( address token, address receiver, uint256 amount ) internal returns (bool transferred) { bytes memory data = abi.encodeWithSignature("transfer(address,uint256)", receiver, amount); // solium-disable-next-line security/no-i...
0.5.3
/// @dev Allows to add a module to the whitelist. /// This can only be done via a Safe transaction. /// @param module Module to be whitelisted.
function enableModule(Module module) public authorized { // Module address cannot be null or sentinel. require(address(module) != address(0) && address(module) != SENTINEL_MODULES, "Invalid module address provided"); // Module cannot be added twice. require(mod...
0.5.3
/// @dev Allows to remove a module from the whitelist. /// This can only be done via a Safe transaction. /// @param prevModule Module that pointed to the module to be removed in the linked list /// @param module Module to be removed.
function disableModule(Module prevModule, Module module) public authorized { // Validate module address and check that it corresponds to module index. require(address(module) != address(0) && address(module) != SENTINEL_MODULES, "Invalid module address provided"); requi...
0.5.3
/// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction.
function execTransactionFromModule(address to, uint256 value, bytes memory data, Enum.Operation operation) public returns (bool success) { // Only whitelisted modules are allowed. require(modules[msg.sender] != address(0), "Method can only be called from an enabled module"); ...
0.5.3
/// @dev Returns array of modules. /// @return Array of modules.
function getModules() public view returns (address[] memory) { // Calculate module count uint256 moduleCount = 0; address currentModule = modules[SENTINEL_MODULES]; while(currentModule != SENTINEL_MODULES) { currentModule = modules[current...
0.5.3
/// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction.
function setupOwners(address[] memory _owners, uint256 _threshold) internal { // Threshold can only be 0 at initialization. // Check ensures that setup function can only be called once. require(threshold == 0, "Owners have already been setup"); // Validate that threshol...
0.5.3
/// @dev Allows to add a new owner to the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @param owner New owner address. /// @param _threshold New threshold.
function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized { // Owner address cannot be null. require(owner != address(0) && owner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. require(owners[own...
0.5.3
/// @dev Allows to remove an owner from the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @param prevOwner Owner that pointed to the owner to be removed in the linked list /// @param owner Owner address to be removed. /// @param _threshold New threshold.
function removeOwner(address prevOwner, address owner, uint256 _threshold) public authorized { // Only allow to remove an owner, if threshold can still be reached. require(ownerCount - 1 >= _threshold, "New owner count needs to be larger than new threshold"); // Validat...
0.5.3
/// @dev Allows to swap/replace an owner from the Safe with another address. /// This can only be done via a Safe transaction. /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list /// @param oldOwner Owner address to be replaced. /// @param newOwner New owner address.
function swapOwner(address prevOwner, address oldOwner, address newOwner) public authorized { // Owner address cannot be null. require(newOwner != address(0) && newOwner != SENTINEL_OWNERS, "Invalid owner address provided"); // No duplicate owners allowed. requ...
0.5.3
/// @dev Allows to update the number of required confirmations by Safe owners. /// This can only be done via a Safe transaction. /// @param _threshold New threshold.
function changeThreshold(uint256 _threshold) public authorized { // Validate that threshold is smaller than number of owners. require(_threshold <= ownerCount, "Threshold cannot exceed owner count"); // There has to be at least one Safe owner. require(_threshol...
0.5.3
/// @dev Returns array of owners. /// @return Array of Safe owners.
function getOwners() public view returns (address[] memory) { address[] memory array = new address[](ownerCount); // populate return array uint256 index = 0; address currentOwner = owners[SENTINEL_OWNERS]; while(currentOwner != SENTINEL_OWNE...
0.5.3
/// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. /// @param to Contract address for optional delegate call. /// @param data Data payload for optional delegate call.
function setupSafe(address[] memory _owners, uint256 _threshold, address to, bytes memory data) internal { setupOwners(_owners, _threshold); // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules setupModules(to, data...
0.5.3
/// @dev Recovers address who signed the message /// @param messageHash operation ethereum signed message hash /// @param messageSignature message `txHash` signature /// @param pos which signature to read
function recoverKey ( bytes32 messageHash, bytes memory messageSignature, uint256 pos ) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = signatureSplit(messageSignature, pos); retur...
0.5.3
/// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s` /// @param pos which signature to read /// @param signatures concatenated rsv signatures
function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns (uint8 v, bytes32 r, bytes32 s) { // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. ...
0.5.3
/// @dev _issueLPTokensForFloat /// @param _token The address of target token. /// @param _transaction The recevier address and amount. /// @param _zerofee The flag to accept zero fees. /// @param _txid The txid which is for recording.
function _issueLPTokensForFloat( address _token, bytes32 _transaction, bool _zerofee, bytes32 _txid ) internal returns (bool) { require(!isTxUsed(_txid), "The txid is already used"); require(_transaction != 0x0, "The transaction is not valid"); // Defi...
0.7.5
/// @dev _checkFlips checks whether the fees are activated. /// @param _token The address of target token. /// @param _amountOfFloat The amount of float.
function _checkFlips(address _token, uint256 _amountOfFloat) internal view returns (uint8) { (uint256 reserveA, uint256 reserveB) = getFloatReserve( address(0), WBTC_ADDR ); uint256 threshold = reserveA .add(reserveB) ...
0.7.5
/// @dev Allows to estimate a Safe transaction. /// This method is only meant for estimation purpose, therfore two different protection mechanism against execution in a transaction have been made: /// 1.) The method can only be called from the safe itself /// 2.) The response is returned with a revert //...
function requiredTxGas(address to, uint256 value, bytes calldata data, Enum.Operation operation) external authorized returns (uint256) { uint256 startGas = gasleft(); // We don't provide an error message here, as we use it to return the estimate // solium-disab...
0.5.3
/** * @dev Should return whether the signature provided is valid for the provided data * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return a bool upon valid or invalid signature with corresponding _data */
function isValidSignature(bytes calldata _data, bytes calldata _signature) external returns (bool isValid) { bytes32 messageHash = getMessageHash(_data); if (_signature.length == 0) { isValid = signedMessages[messageHash] != 0; } else { // cons...
0.5.3
/// @dev Returns the bytes that are hashed to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Fas that should be used for the safe transaction. /// @param dataGas Gas costs for data used to trig...
function encodeTransactionData( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 dataGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) ...
0.5.3
// ============ DPP Functions (create & reset) ============
function createDODOPrivatePool( address baseToken, address quoteToken, uint256 baseInAmount, uint256 quoteInAmount, uint256 lpFeeRate, uint256 i, uint256 k, bool isOpenTwap, uint256 deadLine ) external override ...
0.6.9
/// @dev Setup function sets initial storage of contract. /// @param dx DutchX Proxy Address. /// @param tokens List of whitelisted tokens. /// @param operators List of addresses that can operate the module. /// @param _manager Address of the manager, the safe contract.
function setup(address dx, address[] memory tokens, address[] memory operators, address payable _manager) public { require(address(manager) == address(0), "Manager has already been set"); if (_manager == address(0)){ manager = ModuleManager(msg.sender); } e...
0.5.3
/// @dev Allows to remove token from whitelist. This can only be done via a Safe transaction. /// @param token ERC20 token address.
function removeFromWhitelist(address token) public authorized { require(isWhitelistedToken[token], "Token is not whitelisted"); isWhitelistedToken[token] = false; for (uint i = 0; i<whitelistedTokens.length - 1; i++) if(whitelistedTokens[i] == token){ ...
0.5.3
/** * @dev Configures a domain. * @param name The name to configure. * @param minion The address of the Minion who can assign subdomains * @param _owner The address to assign ownership of this domain to. */
function configureDomainFor(string memory name, address minion, address _owner) public not_stopped owner_only(keccak256(bytes(name))) { bytes32 label = keccak256(bytes(name)); Domain storage domain = domains[label]; if (Registrar(registrar).ownerOf(uint256(label)) != address(this)) { ...
0.5.12
/** * @dev Migrates the domain to a new registrar. * @param name The name of the domain to migrate. */
function migrate(string memory name) public owner_only(keccak256(bytes(name))) { require(stopped); require(migration != address(0x0)); bytes32 label = keccak256(bytes(name)); Domain storage domain = domains[label]; Registrar(registrar).approve(migration, uint256(label));...
0.5.12
/** * @dev Registers a subdomain. * @param label The label hash of the domain to register a subdomain of. * @param subdomain The desired subdomain label. * @param _subdomainOwner The account that should own the newly configured subdomain. */
function register(bytes32 label, string calldata subdomain, address _subdomainOwner, address resolver) external not_stopped { address subdomainOwner = _subdomainOwner; bytes32 domainNode = keccak256(abi.encodePacked(TLD_NODE, label)); bytes32 subdomainLabel = keccak256(bytes(subdomain)); ...
0.5.12
/** * @notice Changes the boosted NFT ids that receive * a bigger daily reward * * @dev Restricted to contract owner * * @param _newBoostedNftIds the new boosted NFT ids */
function setBoostedNftIds(uint256[] memory _newBoostedNftIds) public onlyOwner { // Create array to store old boosted NFTs and emit // event later uint256[] memory oldBoostedNftIds = new uint256[](boostedNftIds.length()); // Empty boosted NFT ids set for (uint256 i = 0; boostedNftIds.length() > 0; ...
0.8.10
/** * @notice Calculates all the NFTs currently staken by * an address * * @dev This is an auxiliary function to help with integration * and is not used anywhere in the smart contract login * * @param _owner address to search staked tokens of * @return an array of token IDs of NFTs that are current...
function tokensStakedByOwner(address _owner) external view returns (uint256[] memory) { // Cache the length of the staked tokens set for the owner uint256 stakedTokensLength = stakedTokens[_owner].length(); // Create an empty array to store the result // Should be the same length as the staked tokens ...
0.8.10
/** * @notice Stake NFTs to start earning ERC-20 * token rewards * * The ERC-20 token rewards will be paid out * when the NFTs are unstaken * * @dev Sender must first approve this contract * to transfer NFTs on his behalf and NFT * ownership is transferred to this contract * for the dur...
function stake(uint256[] memory _tokenIds) public { // Ensure at least one token ID was sent require(_tokenIds.length > 0, "no token IDs sent"); // Enumerate sent token IDs for (uint256 i = 0; i < _tokenIds.length; i++) { // Get token ID uint256 tokenId = _tokenIds[i]; // Store NFT o...
0.8.10
// Helpful for UIs
function collateral_information(address collat_address) external view returns (CollateralInformation memory return_data){ require(enabled_collaterals[collat_address], "Invalid collateral"); // Get the index uint256 idx = collateralAddrToIdx[collat_address]; return_data = ...
0.8.4
// Returns the value of excess collateral (in E18) held globally, compared to what is needed to maintain the global collateral ratio // Also has throttling to avoid dumps during large price movements
function buybackAvailableCollat() public view returns (uint256) { uint256 total_supply = FRAX.totalSupply(); uint256 global_collateral_ratio = FRAX.global_collateral_ratio(); uint256 global_collat_value = FRAX.globalCollateralValue(); if (global_collateral_ratio > PRICE_PRECISION) ...
0.8.4
/* to be called 5 times */
function reserveToken() public onlyOwner { uint supply = totalSupply()+1; uint i; uint j; ReserveList[] memory _acc = new ReserveList[](5); _acc[0].addr=msg.sender; _acc[0].nbOfToken=20; _acc[1].addr= address(0xa5cbD48F84BB626B32b49aC2c7479b88Cd...
0.7.3
/** * Claim token for owners of old SSF */
function claimToken(uint numberOfTokens) public { require(!lockClaim); lockClaim=true; require(claimIsActive, "Claim must be active"); require(totalSupply().add(numberOfTokens) <= MAX_TOKEN, "Purchase would exceed max supply."); uint ssf_balance ; uint...
0.7.3
/** * Mints token - Comes after the claim phase */
function mintToken(uint numberOfTokens) public payable { require(saleIsActive, "Sale must be active"); require(totalSupply().add(numberOfTokens) <= MAX_TOKEN, "Purchase would exceed max supply."); require(tokenPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); ...
0.7.3
/** * Set the starting index once the startingBlox index is known */
function setStartingIndex() onlyOwner public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_TOKEN; // Just a sanity case in the w...
0.7.3
// Returns the missing amount of collateral (in E18) needed to maintain the collateral ratio
function recollatTheoColAvailableE18() public view returns (uint256) { uint256 frax_total_supply = FRAX.totalSupply(); uint256 effective_collateral_ratio = FRAX.globalCollateralValue().mul(PRICE_PRECISION).div(frax_total_supply); // Returns it in 1e6 uint256 desired_collat_e24 = (FR...
0.8.4
// Returns the value of FXS available to be used for recollats // Also has throttling to avoid dumps during large price movements
function recollatAvailableFxs() public view returns (uint256) { uint256 fxs_price = getFXSPrice(); // Get the amount of collateral theoretically available uint256 recollat_theo_available_e18 = recollatTheoColAvailableE18(); // Get the amount of FXS theoretically outputtable ...
0.8.4
// After a redemption happens, transfer the newly minted FXS and owed collateral from this pool // contract to the user. Redemption is split into two functions to prevent flash loans from being able // to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.
function collectRedemption(uint256 col_idx) external returns (uint256 fxs_amount, uint256 collateral_amount) { require(redeemPaused[col_idx] == false, "Redeeming is paused"); require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Too soon"); bool sendFXS = false; ...
0.8.4
/* ========== RESTRICTED FUNCTIONS, CUSTODIAN CAN CALL TOO ========== */
function toggleMRBR(uint256 col_idx, uint8 tog_idx) external onlyByOwnGovCust { if (tog_idx == 0) mintPaused[col_idx] = !mintPaused[col_idx]; else if (tog_idx == 1) redeemPaused[col_idx] = !redeemPaused[col_idx]; else if (tog_idx == 2) buyBackPaused[col_idx] = !buyBackPaused[col_idx]; ...
0.8.4
// Add an AMO Minter
function addAMOMinter(address amo_minter_addr) external onlyByOwnGov { require(amo_minter_addr != address(0), "Zero address detected"); // Make sure the AMO Minter has collatDollarBalance() uint256 collat_val_e18 = IFraxAMOMinter(amo_minter_addr).collatDollarBalance(); require(coll...
0.8.4
// Set the Chainlink oracles
function setOracles(address _frax_usd_chainlink_addr, address _fxs_usd_chainlink_addr) external onlyByOwnGov { // Set the instances priceFeedFRAXUSD = AggregatorV3Interface(_frax_usd_chainlink_addr); priceFeedFXSUSD = AggregatorV3Interface(_fxs_usd_chainlink_addr); // Set the decim...
0.8.4
/** * @notice Migrate assets to a new contract * @dev The caller has to set the addresses list since we don't maintain a list of them * @param _assets List of assets' address to transfer from * @param _to Assets recipient */
function migrateAssets(address[] memory _assets, address _to) external onlyGovernor { require(_assets.length > 0, "assets-list-is-empty"); require(_to != address(this), "new-contract-is-invalid"); for (uint256 i = 0; i < _assets.length; ++i) { IERC20 _asset = IERC20(_assets[i]); ...
0.8.3
///////////////////////////// Only Keeper /////////////////////////////// /// @notice Perform a slippage-protected swap for VSP /// @dev The vVVSP is the beneficiary of the swap /// @dev Have to check allowance to routers before calling this
function swapForVspAndTransferToVVSP(address _tokenIn, uint256 _amountIn) external onlyKeeper { if (_amountIn > 0) { uint256 _minAmtOut = (swapSlippage != 10000) ? _calcAmtOutAfterSlippage( _getOracleRate(_simpleOraclePath(_tokenIn, address...
0.8.3
// called when minting many NFTs // updated_amount = (balanceOG(user) * base_rate * delta / 86400) + amount * initial rate
function updateRewardOnMint(address _user, uint256 _amount) external { require(msg.sender == address(kongzContract), "Can't call this"); uint256 time = min(block.timestamp, END); uint256 timerUser = lastUpdate[_user]; if (timerUser > 0) rewards[_user] = rewards[_user].add(kongzContract.balanceOG(_user)....
0.6.12
// called on transfers
function updateReward(address _from, address _to, uint256 _tokenId) external { require(msg.sender == address(kongzContract)); if (_tokenId < 1001) { uint256 time = min(block.timestamp, END); uint256 timerFrom = lastUpdate[_from]; if (timerFrom > 0) rewards[_from] += kongzContract.balanceOG(_from)...
0.6.12
/** * @dev Virtual implementation of the vesting formula. This returns the amout vested, as a function of time, for * an asset given its total historical allocation. */
function _vestingSchedule(uint256 totalAllocation, uint64 timestamp) internal view virtual returns (uint256) { if (timestamp < start()) { return 0; } else if (timestamp > start() + duration()) { return totalAllocation; } else { return (totalAllocation * (times...
0.8.0
/** * @notice Safe swap via Uniswap / Sushiswap (better rate of the two) * @dev There are many scenarios when token swap via Uniswap can fail, so this * method will wrap Uniswap call in a 'try catch' to make it fail safe. * however, this method will throw minAmountOut is not met * @param _tokenIn address of from t...
function _safeSwap( address _tokenIn, address _tokenOut, uint256 _amountIn, uint256 _minAmountOut, address _to ) internal { (address[] memory path, uint256 amountOut, uint256 rIdx) = swapManager.bestOutputFixedInput(_tokenIn, _tokenOut, _amountIn); ...
0.8.3
/// @dev Return the usd price of asset. mutilpled by 1e18 /// @param _asset The address of asset
function price(address _asset) public view override returns (uint256) { AggregatorV3Interface _feed = feeds[_asset]; require(address(_feed) != address(0), "ChainlinkPriceOracle: not supported"); uint8 _decimals = _feed.decimals(); (, int256 _price, , , ) = _feed.latestRoundData(); return uint...
0.7.6
/** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */
function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool, uint256) { bytes32 computedHash = leaf; uint256 index = 0; for (uint256 i = 0; i < proof.length; i++) { index *= 2; bytes32 proofElement = proof...
0.8.7
// privileged transfer
function transferPrivileged(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success) { if (msg.sender != owner) throw; balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); previligedBalances[_to] = safeAdd(previligedBalances[_t...
0.4.12
// admin only can transfer from the privileged accounts
function transferFromPrivileged(address _from, address _to, uint _value) returns (bool success) { if (msg.sender != owner) throw; uint availablePrevilegedBalance = previligedBalances[_from]; balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); ...
0.4.12
// When is the address's next reward going to become unstakable?
function nextRewardApplicableTime(address account) external view returns (uint256) { require(_stakedTime[account] != 0, "You dont have a stake in progress"); require(_stakedTime[account] <= getTime(), "Your stake takes 24 hours to become available to interact with"); uint256 secondsRemaining = (...
0.5.16
// ------ FUNCTION ------- // // STAKE () // // #require() amount is greater than ZERO // #require() address that is staking is not the contract address // // Insert : token balance to user stakedBalances[address] // Insert : current block timestamp timestamp to stakeTime[address] // Add : ...
function stake(uint256 amount) external nonReentrant notPaused updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); uint256 newStakedBalance = _stakedBalance[msg.sender].add(amount); require(newStakedBalance >= minStakeBalance, "Staked balance is less than minimum stake bal...
0.5.16
// Allows user to unstake tokens without (or with partial) rewards in case of empty reward distribution pool
function exit() public { uint256 reward = Math.min(earned(msg.sender), rewardDistributorBalance); require(reward > 0 || _rewardBalance[msg.sender] > 0 || _stakedBalance[msg.sender] > 0, "No tokens to exit"); _addReward(msg.sender, reward); _stakedTime[msg.sender] = 0; if (_reward...
0.5.16
// ------ FUNCTION ------- // // WITHDRAW UNSTAKED BALANCE (uint256 amount) // // updateReward() // // #require() that the amount of tokens specified to unstake is above ZERO // #require() that the user has a current unstakingBalance[address] above amount specified to withdraw // #require...
function withdrawUnstakedBalance(uint256 amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "Account does not have an unstaking balance"); require(_unstakingBalance[msg.sender] >= amount, "Account does not have that much balance unstaked"); require(_unstakingTime[msg.sen...
0.5.16
// ------ FUNCTION ------- // // WITHDRAW REWARD () // // updateReward() // // #require() that the reward balance of the user is above ZERO // // TRANSFER : transfer reward balance to address that called the function // // MODIFY : update rewardBalance to ZERO // // EXIT //
function withdrawReward() public updateReward(msg.sender) { uint256 reward = _rewardBalance[msg.sender]; require(reward > 0, "You have not earned any rewards yet"); _rewardBalance[msg.sender] = 0; _unstakingBalance[msg.sender] = _unstakingBalance[msg.sender].add(reward); _unstaki...
0.5.16
// ------ FUNCTION ------- // // REMOVE REWARD SUPPLY | ONLY OWNER // // #require() that the amount of tokens being removed is above ZERO // #require() that the amount is equal to or below the rewardDistributorBalance // #require() that the amount is equal to or below the totalSupply of tokens in the...
function removeRewardSupply(uint256 amount) external onlyOwner nonReentrant { require(amount > 0, "Cannot withdraw 0"); require(amount <= rewardDistributorBalance, "rewardDistributorBalance has less tokens than requested"); require(amount <= _totalSupply, "Amount is greater that total supply"); ...
0.5.16
//-------------------------------------------------------------------------- // BOOSTER //--------------------------------------------------------------------------
function buyBooster(uint256 idx) public payable { require(idx < numberOfBoosts); BoostData storage b = boostData[idx]; if (msg.value < b.basePrice || msg.sender == b.owner) revert(); address beneficiary = b.owner; uint256 devFeePrize = devFee(b.basePrice); ...
0.4.25
/** * @dev subtract virus of player * @param _addr player address * @param _value number virus subtract */
function subVirus(address _addr, uint256 _value) public onlyContractsMiniGame { updateVirus(_addr); Player storage p = players[_addr]; uint256 subtractVirus = SafeMath.mul(_value,VIRUS_MINING_PERIOD); if ( p.virusNumber < subtractVirus ) { revert(); } ...
0.4.25
/** * @dev get player data * @param _addr player address */
function getPlayerData(address _addr) public view returns( uint256 _virusNumber, uint256 _currentVirus, uint256 _research, uint256 _researchPerDay, uint256 _lastUpdateTime, uint256[8] _engineersCount ) { Player storage p = pl...
0.4.25
// ------ FUNCTION ------- // // SET REWARDS INTERVAL () ONLY OWNER // // #require() that reward interval sullpied as argument is greater than 1 and less than 365 inclusive // // MODIFY : rewardInterval to supplied _rewardInterval // // EMIT : update reward interval // // EXIT //
function setRewardsInterval(uint256 _rewardInterval) external onlyOwner { require( _rewardInterval >= 1 && _rewardInterval <= 365, "Staking reward interval must be between 1 and 365 inclusive" ); rewardInterval = _rewardInterval * 1 days; emit RewardsDurationUpdat...
0.5.16
// ------ FUNCTION -------# // // SET REWARDS DIVIDER () ONLY OWNER // // #require() that reward divider sullpied as argument is greater than original divider // // MODIFY : rewardIntervalDivider to supplied _rewardInterval // // EXIT //
function updateChunkUsersRewards(uint256 startIndex, uint256 endIndex) external onlyOwner { uint256 length = allAddress.length; require(endIndex <= length, "Cant end on index greater than length of addresses"); require(endIndex > startIndex, "Nothing to iterate over"); for (ui...
0.5.16
/// @notice Transfers '_value' in aToken to the '_to' address /// @param _to The recipient address /// @param _value The amount of wei to transfer
function transfer(address _to, uint256 _value) public returns (bool success) { /* Check if sender has balance and for overflows */ require(balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]); /* Check if amount is nonzero */ require(_value > 0); ...
0.4.25
/// @notice Sells aToken in exchnage for wei at the current bid /// price, reduces resreve /// @return Proceeds of wei from sale of aToken
function sell(uint256 amount) public returns (uint256 revenue){ uint256 a = 0; require(initialSaleComplete); require(balances[msg.sender] >= amount); // checks if the sender has enough to sell a = _totalSupply - amount; uint256 p = 0; ui...
0.4.25
/// @notice Compute '_k * (1+1/_q) ^ _n', with precision '_p' /// @dev The higher the precision, the higher the gas cost. It should be /// something around the log of 'n'. When 'p == n', the /// precision is absolute (sans possible integer overflows). /// Much smaller values are sufficient to get a great approximation....
function fracExp(uint256 _k, uint256 _q, uint256 _n, uint256 _p) internal pure returns (uint256) { uint256 s = 0; uint256 N = 1; uint256 B = 1; for (uint256 i = 0; i < _p; ++i){ s += _k * N / B / (_q**i); N = N * (_n-i); B = B * (i+1); } return s; ...
0.4.25
/// @notice Compute the natural logarithm /// @notice outputs ln()*FIXED_3*lnr*1e18 /// @dev This functions assumes that the numerator is larger than or equal /// to the denominator, because the output would be negative otherwise. /// @param _numerator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1 /// @param ...
function ln_fixed3_lnr_18(uint256 _numerator, uint256 _denominator) internal pure returns (uint256) { assert(_numerator <= MAX_NUM); uint256 res = 0; uint256 x = _numerator * FIXED_1 / _denominator; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0...
0.4.25
/// @notice Compute the largest integer smaller than or equal to /// the binary logarithm of the input /// @param _n Operand of the function /// @return Floor(Log2(_n))
function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations ...
0.4.25
/// @notice Round the operand to one decimal place /// @param _n Operand to be rounded /// @param _m Divisor /// @return ROUND(_n/_m)
function round(uint256 _n, uint256 _m) internal pure returns (uint256) { uint256 res = 0; uint256 p =_n/_m; res = _n-(_m*p); if(res >= 1) { res = p+1; } else { res = p; } return res;...
0.4.25
/** * @dev Claims airdropped tokens. * @param amount The amount of the claim being made. * @param delegate The address the tokenholder wants to delegate their votes to. * @param merkleProof A merkle proof proving the claim is valid. */
function claimTokens(uint256 amount, address delegate, bytes32[] calldata merkleProof) external { bytes32 leaf = keccak256(abi.encodePacked(msg.sender, amount)); (bool valid, uint256 index) = MerkleProof.verify(merkleProof, merkleRoot, leaf); require(valid, "ENS: Valid proof required."); ...
0.8.7
/** * @dev Mints new tokens. Can only be executed every `minimumMintInterval`, by the owner, and cannot * exceed `mintCap / 10000` fraction of the current total supply. * @param dest The address to mint the new tokens to. * @param amount The quantity of tokens to mint. */
function mint(address dest, uint256 amount) external onlyOwner { require(amount <= (totalSupply() * mintCap) / 10000, "ENS: Mint exceeds maximum amount"); require(block.timestamp >= nextMint, "ENS: Cannot mint yet"); nextMint = block.timestamp + minimumMintInterval; _mint(dest, amount);...
0.8.7
/** * Set some Giraffes aside */
function reserveGiraffes(uint256 numberOfTokens) public onlyOwner { uint256 i; for (i = 0; i < numberOfTokens; i++) { uint256 index = totalSupply(); if (index < maxGiraffes) { setGiraffePortionTimesHundredByIndex(index, 0); _safeMint(msg.send...
0.8.6
/** * Mints Giraffes */
function mintGiraffe(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint a Giraffe"); require( numberOfTokens <= maxGiraffesPurchase, "Can only mint 10 Giraffes at a time" ); require( totalSupply().add(num...
0.8.6
// Function to use for staking with an event where cardId and cardAmount are fixed
function stake(uint256 _eventId) public { StakingEvent storage _event = stakingEvents[_eventId]; UserInfo storage _userInfo = userInfo[msg.sender][_eventId]; require(block.number <= _event.blockEventClose, "Event is closed"); require(_userInfo.isCompleted == false, "Address already...
0.6.6
/*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/
function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math d...
0.8.7
// Claim staked cards + reward
function claim(uint256 _eventId) public { StakingEvent storage _event = stakingEvents[_eventId]; UserInfo storage _userInfo = userInfo[msg.sender][_eventId]; require(block.number >= _userInfo.blockEnd, "BlockEnd not reached"); _userInfo.isCompleted = true; pepemonFactory...
0.6.6
/*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); }
0.8.7
/*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/
function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-enco...
0.8.7
/*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/
function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // ...
0.8.7
// Withdraw staked cards, but reset event progress
function cancel(uint256 _eventId) public { UserInfo storage _userInfo = userInfo[msg.sender][_eventId]; require(_userInfo.isCompleted == false, "Address already completed event"); require(_userInfo.blockEnd != 0, "Address is not staked for this event"); delete _userInfo.isComplet...
0.6.6
/// @notice Update merkle root and rate /// @param _merkleRoot root of merkle tree /// @param _rate price of pCNV in DAI/FRAX
function setRound( bytes32 _merkleRoot, uint256 _rate ) external onlyConcave { // push new root to array of all roots - for viewing roots.push(_merkleRoot); // update merkle root merkleRoot = _merkleRoot; // update rate rate = _rate; ...
0.8.7
/// @notice mint pCNV by providing merkle proof and depositing DAI; uses EIP-2612 permit to save a transaction /// @param to whitelisted address pCNV will be minted to /// @param tokenIn address of tokenIn user wishes to deposit (DAI) /// @param maxAmount max amount of DAI sender c...
function mintWithPermit( address to, address tokenIn, uint256 maxAmount, uint256 amountIn, bytes32[] calldata proof, uint256 permitDeadline, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountOut) { // Make sure ...
0.8.7
// Keeping some NFTs aside
function reserveNft(uint256 reserve) public onlyOwner { uint supply = totalSupply(); uint counter; for (counter = 0; counter < reserve; counter++) { uint reserved_id = supply + counter; _safeMint(msg.sender, reserved_id); // string memory tokenURI = stri...
0.6.6
// The main minting function
function mint(uint256 amount) public payable { require(isSaleActive, "Sale must be active to mint NFT"); require(amount <= MAX_NFT, "Amount must be less than MAX_NFT"); require(totalSupply().add(amount) <= MAX_NFT, "Total supply + amount must be less than MAX_NFT"); require(nftPrice....
0.6.6
/// Withdraw a bid that was overbid.
function withdraw() public { uint amount = pendingReturns[msg.sender]; require (amount > 0); // It is important to set this to zero because the recipient // can call this function again as part of the receiving call // before `send` returns. totalReturns -= amou...
0.4.21
// pair , 100
function _reflect(address account, uint256 amount) internal { require(account != address(0), "reflect from the zero address"); // from(pair) , to(this) , 100DHOld _rawTransfer(account, address(this), amount); totalReflected += amount; emit Transfer(account, address(th...
0.8.0
// modified from OpenZeppelin ERC20
function _rawTransfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "transfer from the zero address"); require(recipient != address(0), "transfer to the zero address"); uint256 senderBalance = balanceOf(sender); require(senderBalance >= amou...
0.8.0
// function to claim all the tokens locked for a user, after the locking period
function claimAllForUser(uint256 r, address user) public { require(!emergencyFlag, "Emergency mode, cannot access this function"); require(r>latestCounterByUser[user], "Increase right header, already claimed till this"); require(r<=lockInfoByUser[user].length, "Decrease right header, it exceeds ...
0.6.12