lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.14
/**
 * Accumulate the amount FIN mined by depositing between _lastBlock and _currentBlock
 */
function calculateDepositFIN(uint256 _lastBlock, address _token, address _accountAddr, uint256 _currentBlock) internal {
        Bank bank = globalConfig.bank();

        uint256 indexDifference = bank.depositFINRateIndex(_token, _currentBlock)
            .sub(bank.depositFINRateIndex(_token, _lastBlock));
        uint256 getFIN = getDepositBalanceCurrent(_token, _accountAddr)
            .mul(indexDifference)
            .div(bank.depositeRateIndex(_token, _currentBlock));
        FINAmount[_accountAddr] = FINAmount[_accountAddr].add(getFIN);
    }
// Solidity 0.5.14
/**
 * The function is called in Bank.deposit(), Bank.withdraw() and Accounts.claim() functions.
 * The function should be called AFTER the newRateIndexCheckpoint function so that the account balances are
 * accurate, and BEFORE the account balance acutally updated due to deposit/withdraw activities.
 */
function updateDepositFINIndex(address _token) public onlyAuthorized{
        uint currentBlock = getBlockNumber();
        uint deltaBlock;
        // If it is the first deposit FIN rate checkpoint, set the deltaBlock value be 0 so that the first
        // point on depositFINRateIndex is zero.
        deltaBlock = lastDepositFINRateCheckpoint[_token] == 0 ? 0 : currentBlock.sub(lastDepositFINRateCheckpoint[_token]);
        // If the totalDeposit of the token is zero, no FIN token should be mined and the FINRateIndex is unchanged.
        depositFINRateIndex[_token][currentBlock] = depositFINRateIndex[_token][lastDepositFINRateCheckpoint[_token]].add(
            getTotalDepositStore(_token) == 0 ? 0 : depositeRateIndex[_token][lastCheckpoint[_token]]
                .mul(deltaBlock)
                .mul(globalConfig.tokenInfoRegistry().depositeMiningSpeeds(_token))
                .div(getTotalDepositStore(_token)));
        lastDepositFINRateCheckpoint[_token] = currentBlock;

        emit UpdateDepositFINIndex(_token, depositFINRateIndex[_token][currentBlock]);
    }
// Solidity 0.5.14
/**
 * Calculate a token deposite rate of current block
 * @param _token token address
 * @dev This is an looking forward estimation from last checkpoint and not the exactly rate that the user will pay or earn.
 */
function depositeRateIndexNow(address _token) public view returns(uint) {
        uint256 lcp = lastCheckpoint[_token];
        // If this is the first checkpoint, set the index be 1.
        if(lcp == 0)
            return INT_UNIT;

        uint256 lastDepositeRateIndex = depositeRateIndex[_token][lcp];
        uint256 depositRatePerBlock = getDepositRatePerBlock(_token);
        // newIndex = oldIndex*(1+r*delta_block). If delta_block = 0, i.e. the last checkpoint is current block, index doesn't change.
        return lastDepositeRateIndex.mul(getBlockNumber().sub(lcp).mul(depositRatePerBlock).add(INT_UNIT)).div(INT_UNIT);
    }
// Solidity 0.5.14
/**
 * Calculate a token borrow rate of current block
 * @param _token token address
 */
function borrowRateIndexNow(address _token) public view returns(uint) {
        uint256 lcp = lastCheckpoint[_token];
        // If this is the first checkpoint, set the index be 1.
        if(lcp == 0)
            return INT_UNIT;
        uint256 lastBorrowRateIndex = borrowRateIndex[_token][lcp];
        uint256 borrowRatePerBlock = getBorrowRatePerBlock(_token);
        return lastBorrowRateIndex.mul(getBlockNumber().sub(lcp).mul(borrowRatePerBlock).add(INT_UNIT)).div(INT_UNIT);
    }
// Solidity 0.5.14
/**
 * Withdraw a token from an address
 * @param _from address to be withdrawn from
 * @param _token token address
 * @param _amount amount to be withdrawn
 * @return The actually amount withdrawed, which will be the amount requested minus the commission fee.
 */
function withdraw(address _from, address _token, uint256 _amount) external onlyAuthorized returns(uint) {

        require(_amount != 0, "Amount is zero");

        // Add a new checkpoint on the index curve.
        newRateIndexCheckpoint(_token);
        updateDepositFINIndex(_token);

        // Withdraw from the account
        uint amount = globalConfig.accounts().withdraw(_from, _token, _amount);

        // Update pool balance
        // Update the amount of tokens in compound and loans, i.e. derive the new values
        // of C (Compound Ratio) and U (Utilization Ratio).
        uint compoundAmount = update(_token, amount, ActionType.WithdrawAction);

        // Check if there are enough tokens in the pool.
        if(compoundAmount > 0) {
            globalConfig.savingAccount().fromCompound(_token, compoundAmount);
        }

        return amount;
    }
// Solidity 0.4.18
// Checks if funds of a given address are time-locked
function timeLocked(address _spender)
    public
    returns (bool)
    {
        if (releaseTimes[_spender] == 0) {
            return false;
        }

        // If time-lock is expired, delete it
        var _time = timeMode == TimeMode.Timestamp ? block.timestamp : block.number;
        if (releaseTimes[_spender] <= _time) {
            delete releaseTimes[_spender];
            return false;
        }

        return true;
    }
// Solidity 0.5.15
// return normalized rate
function normalizeRate(address src, address dest, uint256 rate) public view
    returns(uint)
  {
    RateAdjustment memory adj = rateAdjustment[src][dest];
    if (adj.factor == 0) {
      uint srcDecimals = _getDecimals(src);
      uint destDecimals = _getDecimals(dest);
      if (srcDecimals != destDecimals) {
        if (srcDecimals > destDecimals) {
          adj.multiply = true;
          adj.factor = 10 ** (srcDecimals - destDecimals);
        } else {
          adj.multiply = false;
          adj.factor = 10 ** (destDecimals - srcDecimals);
        }
      }
    }
    if (adj.factor > 1) {
      rate = adj.multiply
      ? rate.mul(adj.factor)
      : rate.div(adj.factor);
    }
    return rate;
  }
// Solidity 0.6.12
// Deposit LP tokens to MasterChef for SUSHI/USDCow allocation.
function deposit(uint256 _pid, uint256 _amount) public payable {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        
        updatePool(_pid);
        
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
        
            safeSushiTransfer(msg.sender, pending);
        }
        
        if (address(pool.token) == WETH) {
            if(_amount > 0) {
                pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
            }
            
            if (msg.value > 0) {
                IWETH(WETH).deposit{value: msg.value}();
                _amount = _amount.add(msg.value);
            }
        } else if (_amount > 0) {
            pool.token.safeTransferFrom(address(msg.sender), address(this), _amount);
        }
        
        if (_amount > 0) {
            pool.amount = pool.amount.add(_amount);
            user.amount = user.amount.add(_amount);
        }
        
        user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }
// Solidity 0.6.12
// Safe sushi/usdcow transfer/mint function, just in case if rounding error causes pool to not have enough SUSHIs/USDCows/USDCs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
        if (_amount > 0) {
            tryRebase();
        }
        
        uint256 cowBal = sushi.balanceOf(sushi.uniswapV2Pair());
        uint256 usdcBal = sushi.usdc().balanceOf(sushi.uniswapV2Pair());
        
        if (cowBal < usdcBal.mul(1000)) {
            uint256 usdcAmount = _amount.div(1000);
            
            while (sushi.usdc().balanceOf(address(this)) < usdcAmount) {
                sushi.mint(address(this), _amount);
                
                address[] memory path = new address[](2);
                path[0] = address(sushi);
                path[1] = address(sushi.usdc());
                
                sushi.uniswapV2Router().swapExactTokensForTokens(_amount, 0, path, address(this), now.add(120));
            }
            
            sushi.usdc().transfer(_to, usdcAmount);
        } else {
            sushi.mint(_to, _amount);
            sushi.mint(devaddr, _amount.div(100));
        }
    }
// Solidity 0.4.19
/**
 * @notice External function to transfers a token to another address.
 * @param _to The address of the recipient, can be a user or contract.
 * @param _tokenId The ID of the token to transfer.
 */
function transfer(address _to, uint _tokenId) whenNotPaused external {
        // Safety check to prevent against an unexpected 0x0 default.
        require(_to != address(0));

        // Disallow transfers to this contract to prevent accidental misuse.
        require(_to != address(this));

        // You can only send your own token.
        require(_owns(msg.sender, _tokenId));

        // Reassign ownership, clear pending approvals, emit Transfer event.
        _transfer(msg.sender, _to, _tokenId);
    }
// Solidity 0.4.19
/**
 * @dev The external function that creates a new dungeon and stores it, only contract owners
 *  can create new token, and will be restricted by the DUNGEON_CREATION_LIMIT.
 *  Will generate a Mint event, a  NewDungeonFloor event, and a Transfer event.
 * @param _difficulty The difficulty of the new dungeon.
 * @param _seedGenes The seed genes of the new dungeon.
 * @return The dungeon ID of the new dungeon.
 */
function createDungeon(uint _difficulty, uint _seedGenes, address _owner) eitherOwner external returns (uint) {
        // Ensure the total supply is within the fixed limit.
        require(totalSupply() < DUNGEON_CREATION_LIMIT);

        // UPDATE STORAGE
        // Create a new dungeon.
        dungeons.push(Dungeon(uint32(now), 0, uint16(_difficulty), 0, 0, 0, _seedGenes, 0));

        // Token id is the index in the storage array.
        uint newTokenId = dungeons.length - 1;

        // Emit the token mint event.
        Mint(_owner, newTokenId, _difficulty, _seedGenes);

        // Initialize the fist floor with using the seedGenes, this will emit the NewDungeonFloor event.
        addDungeonNewFloor(newTokenId, 0, _seedGenes);

        // This will assign ownership, and also emit the Transfer event.
        _transfer(0, _owner, newTokenId);

        return newTokenId;
    }
// Solidity 0.4.19
/**
 * @dev The external function to add another dungeon floor by its ID,
 *  only contract owners can alter dungeon state.
 *  Will generate both a NewDungeonFloor event.
 */
function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner public {
        require(_id < totalSupply());

        Dungeon storage dungeon = dungeons[_id];

        dungeon.floorNumber++;
        dungeon.floorCreationTime = uint32(now);
        dungeon.rewards = uint128(_newRewards);
        dungeon.floorGenes = _newFloorGenes;

        // Emit the NewDungeonFloor event.
        NewDungeonFloor(now, _id, dungeon.floorNumber, dungeon.rewards, dungeon.floorGenes);
    }
// Solidity 0.4.19
/**
 * @dev An external function that creates a new hero and stores it,
 *  only contract owners can create new token.
 *  method doesn't do any checking and should only be called when the
 *  input data is known to be valid.
 * @param _genes The gene of the new hero.
 * @param _owner The inital owner of this hero.
 * @return The hero ID of the new hero.
 */
function createHero(uint _genes, address _owner) external returns (uint) {
        // UPDATE STORAGE
        // Create a new hero.
        heroes.push(Hero(uint64(now), _genes));

        // Token id is the index in the storage array.
        uint newTokenId = heroes.length - 1;

        // Emit the token mint event.
        Mint(_owner, newTokenId, _genes);

        // This will assign ownership, and also emit the Transfer event.
        _transfer(0, _owner, newTokenId);

        return newTokenId;
    }
// Solidity 0.4.19
/**
 * @dev An internal function to calculate the power of player, or difficulty of a dungeon floor,
 *  if the total heroes power is larger than the current dungeon floor difficulty, the heroes win the challenge.
 */
function _getGenesPower(uint _genes) internal pure returns (uint) {
        // Calculate total stats power.
        uint statsPower;

        for (uint i = 0; i < 4; i++) {
            statsPower += _genes % 32;
            _genes /= 32 ** 4;
        }

        // Calculate total stats power.
        uint equipmentPower;
        bool isSuper = true;

        for (uint j = 4; j < 12; j++) {
            uint curGene = _genes % 32;
            equipmentPower += curGene;
            _genes /= 32 ** 4;

            if (equipmentPower != curGene * (j - 3)) {
                isSuper = false;
            }
        }

        // Calculate super power.
        if (isSuper) {
            equipmentPower *= 2;
        }

        return statsPower + equipmentPower + 12;
    }
// Solidity 0.4.19
/**
 * @dev The main public function to call when a player challenge a dungeon,
 *  it determines whether if the player successfully challenged the current floor.
 *  Will generate a DungeonChallenged event.
 */
function challenge(uint _dungeonId) external payable whenNotPaused canChallenge(_dungeonId) {
        // Get the dungeon details from the token contract.
        uint difficulty;
        uint seedGenes;
        (,,difficulty,,,,seedGenes,) = dungeonTokenContract.dungeons(_dungeonId);

        // Checks for payment, any exceeding funds will be transferred back to the player.
        uint requiredFee = difficulty * challengeFeeMultiplier;
        require(msg.value >= requiredFee);

        // ** STORAGE UPDATE **
        // Increment the accumulated rewards for the dungeon.
        dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee);

        // Calculate any excess funds and make it available to be withdrawed by the player.
        asyncSend(msg.sender, msg.value - requiredFee);

        // Split the challenge function into multiple parts because of stack too deep error.
        _challengePart2(_dungeonId);
    }
// Solidity 0.4.19
/**
 * Split the challenge function into multiple parts because of stack too deep error.
 */
function _getFirstHeroGenesAndInitialize(uint _dungeonId) private returns (uint heroGenes) {
        uint seedGenes;
        (,,,,,,seedGenes,) = dungeonTokenContract.dungeons(_dungeonId);

        // Get the first hero of the player.
        uint heroId;

        if (heroTokenContract.balanceOf(msg.sender) == 0) {
            // Assign the first hero using the seed genes of the dungeon for new player.
            heroId = heroTokenContract.createHero(seedGenes, msg.sender);
        } else {
            heroId = heroTokenContract.ownerTokens(msg.sender, 0);
        }

        // Get the hero genes from token storage.
        (,heroGenes) = heroTokenContract.heroes(heroId);
    }
// Solidity 0.4.19
/**
 * @dev The external function to get all the relevant information about a specific dungeon by its ID.
 * @param _id The ID of the dungeon.
 */
function getDungeonDetails(uint _id) external view returns (uint creationTime, uint status, uint difficulty, uint floorNumber, uint floorCreationTime, uint rewards, uint seedGenes, uint floorGenes) {
        require(_id < dungeonTokenContract.totalSupply());

        (creationTime, status, difficulty, floorNumber, floorCreationTime, rewards, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_id);
    }
// Solidity 0.4.20
// Check if the player won or refund if randomness proof failed
function checkIfWon(uint _currentQueryId, uint _randomNumber) private {
    bool win;
    if (_randomNumber != 101) {
      if (_randomNumber < 90) {
        win = true;
        sendPayout(_currentQueryId, ((queryIdMap[_currentQueryId].betValue*110)/100));
      } else {
        win = false;
        sendOneWei(_currentQueryId);
      }
    } else {
      win = false;
      sendRefund(_currentQueryId);
    }
    logBet(_currentQueryId, _randomNumber, win);
  }
// Solidity 0.5.9
///@notice Adds the specified address to the list of administrators.
///@param account The address to add to the administrator list.
///@return Returns true if the operation was successful.
function addAdmin(address account) external onlyAdmin returns(bool) {
    require(account != address(0), "Invalid address.");
    require(!_admins[account], "This address is already an administrator.");

    require(account != super.owner(), "The owner cannot be added or removed to or from the administrator list.");

    _admins[account] = true;

    emit AdminAdded(account);
    return true;
  }
// Solidity 0.5.9
///@notice Adds multiple addresses to the administrator list.
///@param accounts The account addresses to add to the administrator list.
///@return Returns true if the operation was successful.
function addManyAdmins(address[] calldata accounts) external onlyAdmin returns(bool) {
    for(uint8 i = 0; i < accounts.length; i++) {
      address account = accounts[i];

      ///Zero address cannot be an admin.
      ///The owner is already an admin and cannot be assigned.
      ///The address cannot be an existing admin.
      if(account != address(0) && !_admins[account] && account != super.owner()) {
        _admins[account] = true;

        emit AdminAdded(accounts[i]);
      }
    }

    return true;
  }
// Solidity 0.5.9
///@notice Removes the specified address from the list of administrators.
///@param account The address to remove from the administrator list.
///@return Returns true if the operation was successful.
function removeAdmin(address account) external onlyAdmin returns(bool) {
    require(account != address(0), "Invalid address.");
    require(_admins[account], "This address isn't an administrator.");

    //The owner cannot be removed as admin.
    require(account != super.owner(), "The owner cannot be added or removed to or from the administrator list.");

    _admins[account] = false;
    emit AdminRemoved(account);
    return true;
  }
// Solidity 0.5.9
///@notice Ensures that the requested ERC20 transfer amount is within the maximum allowed limit.
///@param amount The amount being requested to be transferred out of this contract.
///@return Returns true if the transfer request is valid and acceptable.
function checkIfValidTransfer(uint256 amount) public view returns(bool) {
    require(amount > 0, "Access is denied.");

    if(_maximumTransfer > 0) {
      require(amount <= _maximumTransfer, "Sorry but the amount you're transferring is too much.");
    }

    return true;
  }
// Solidity 0.5.9
///@notice Allows the sender to transfer tokens to the beneficiary.
///@param token The ERC20 token to transfer.
///@param destination The destination wallet address to send funds to.
///@param amount The amount of tokens to send to the specified address.
///@return Returns true if the operation was successful.
function transferTokens(address token, address destination, uint256 amount)
  external onlyAdmin whenNotPaused
  returns(bool) {
    require(checkIfValidTransfer(amount), "Access is denied.");

    ERC20 erc20 = ERC20(token);

    require
    (
      erc20.balanceOf(address(this)) >= amount,
      "You don't have sufficient funds to transfer amount that large."
    );


    erc20.safeTransfer(destination, amount);


    emit TransferPerformed(token, msg.sender, destination, amount);
    return true;
  }
// Solidity 0.5.9
///@notice Allows the sender to transfer Ethers to the beneficiary.
///@param destination The destination wallet address to send funds to.
///@param amount The amount of Ether in wei to send to the specified address.
///@return Returns true if the operation was successful.
function transferEthers(address payable destination, uint256 amount)
  external onlyAdmin whenNotPaused
  returns(bool) {
    require(checkIfValidWeiTransfer(amount), "Access is denied.");

    require
    (
      address(this).balance >= amount,
      "You don't have sufficient funds to transfer amount that large."
    );


    destination.transfer(amount);


    emit EtherTransferPerformed(msg.sender, destination, amount);
    return true;
  }
// Solidity 0.5.9
///@notice Allows the requester to perform ERC20 bulk transfer operation.
///@param token The ERC20 token to bulk transfer.
///@param destinations The destination wallet addresses to send funds to.
///@param amounts The respective amount of funds to send to the specified addresses.
///@return Returns true if the operation was successful.
function bulkTransfer(address token, address[] calldata destinations, uint256[] calldata amounts)
  external onlyAdmin whenNotPaused
  returns(bool) {
    require(destinations.length == amounts.length, "Invalid operation.");

    //Saving gas by first determining if the sender actually has sufficient balance
    //to post this transaction.
    uint256 requiredBalance = sumOf(amounts);

    //Verifying whether or not this transaction exceeds the maximum allowed ERC20 transfer cap.
    require(checkIfValidTransfer(requiredBalance), "Access is denied.");

    ERC20 erc20 = ERC20(token);

    require
    (
      erc20.balanceOf(address(this)) >= requiredBalance,
      "You don't have sufficient funds to transfer amount this big."
    );


    for (uint256 i = 0; i < destinations.length; i++) {
      erc20.safeTransfer(destinations[i], amounts[i]);
    }

    emit BulkTransferPerformed(token, msg.sender, destinations.length, requiredBalance);
    return true;
  }
// Solidity 0.6.12
/// #if_succeeds {:msg "The sell amount should be correct - case _amount = 0"} 
/// _amount == 0 ==> $result == 0;
/// #if_succeeds {:msg "The sell amount should be correct - case _reserveWeight = MAX_WEIGHT"}
/// _reserveWeight == 1000000 ==> $result == _removeSellTax(_reserveBalance.mul(_amount) / _supply);
function saleTargetAmount(
        uint256 _supply,
        uint256 _reserveBalance,
        uint32 _reserveWeight,
        uint256 _amount
    ) public view returns (uint256) {
        uint256 reserveValue = _curveAddress.saleTargetAmount(
            _supply,
            _reserveBalance,
            _reserveWeight,
            _amount
        );
        uint256 gross = _removeSellTax(reserveValue);
        return gross;
    }
// Solidity 0.6.12
/// #if_succeeds {:msg "The fundCost amount should be correct - case _amount = 0"}
/// _amount == 0 ==> $result == 0;
/// #if_succeeds {:msg "The fundCost amount should be correct - case _reserveRatio = MAX_WEIGHT"}
/// _reserveRatio == 1000000 ==> $result == _addBuyTax(_curveAddress.fundCost(_supply, _reserveBalance, _reserveRatio, _amount));
function fundCost(
        uint256 _supply,
        uint256 _reserveBalance,
        uint32 _reserveRatio,
        uint256 _amount
    ) public view returns (uint256) {
        uint256 reserveTokenCost = _curveAddress.fundCost(
            _supply,
            _reserveBalance,
            _reserveRatio,
            _amount
        );
        uint256 net = _addBuyTax(reserveTokenCost);
        return net;
    }