lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.10
/// @dev Settle system debt in MakerDAO and free remaining collateral.
function settleTreasury() public {
        require(
            live == false,
            "Unwind: Unwind first"
        );
        (uint256 ink, uint256 art) = vat.urns(WETH, address(treasury));
        require(ink > 0, "Unwind: Nothing to settle");

        _treasuryWeth = ink;                            // We will need this to skim profits
        vat.fork(                                      // Take the treasury vault
            WETH,
            address(treasury),
            address(this),
            toInt(ink),
            toInt(art)
        );
        end.skim(WETH, address(this));                // Settle debts
        end.free(WETH);                               // Free collateral
        uint256 gem = vat.gem(WETH, address(this));   // Find out how much collateral we have now
        wethJoin.exit(address(this), gem);            // Take collateral out
        settled = true;
    }
// Solidity 0.6.10
/// @dev Put all chai savings in MakerDAO and exchange them for weth
function cashSavings() public {
        require(
            end.tag(WETH) != 0,
            "Unwind: End.sol not caged"
        );
        require(
            end.fix(WETH) != 0,
            "Unwind: End.sol not ready"
        );
        
        uint256 chaiTokens = chai.balanceOf(address(treasury));
        require(chaiTokens > 0, "Unwind: Nothing to cash");
        chai.exit(address(treasury), chaiTokens);           // Get the chai as dai

        uint256 daiTokens = dai.balanceOf(address(this));   // Find out how much is the chai worth
        daiJoin.join(address(this), daiTokens);             // Put the dai into MakerDAO
        end.pack(daiTokens);                                // Into End.sol, more exactly
        end.cash(WETH, daiTokens);                          // Exchange the dai for weth
        uint256 gem = vat.gem(WETH, address(this));         // Find out how much collateral we have now
        wethJoin.exit(address(this), gem);                  // Take collateral out
        cashedOut = true;

        _fix = end.fix(WETH);
        _chi = pot.chi();
    }
// Solidity 0.6.10
/// @dev Settles a series position in Controller for any user, and then returns any remaining collateral as weth using the unwind Dai to Weth price.
/// @param collateral Valid collateral type.
/// @param user User vault to settle, and wallet to receive the corresponding weth.
function settle(bytes32 collateral, address user) public {
        (uint256 tokens, uint256 debt) = controller.erase(collateral, user);
        require(tokens > 0, "Unwind: Nothing to settle");

        uint256 remainder;
        if (collateral == WETH) {
            remainder = subFloorZero(tokens, daiToFixWeth(debt, _fix));
        } else if (collateral == CHAI) {
            remainder = daiToFixWeth(subFloorZero(chaiToDai(tokens, _chi), debt), _fix);
        }
        require(weth.transfer(user, remainder));
    }
// Solidity 0.6.10
/// @dev Redeems FYDai for weth for any user. FYDai.redeem won't work if MakerDAO is in shutdown.
/// @param maturity Maturity of an added series
/// @param user Wallet containing the fyDai to burn.
function redeem(uint256 maturity, address user) public {
        IFYDai fyDai = controller.series(maturity);
        require(fyDai.unlocked() == 1, "fyDai is still locked");
        uint256 fyDaiAmount = fyDai.balanceOf(user);
        require(fyDaiAmount > 0, "Unwind: Nothing to redeem");

        fyDai.burn(user, fyDaiAmount);
        require(
            weth.transfer(
                user,
                daiToFixWeth(muld(fyDaiAmount, fyDai.chiGrowth()), _fix)
            )
        );
    }
// Solidity 0.5.17
/**
 @notice This function adds liquidity to a Curve pool with ETH or ERC20 tokens
 @param _fromTokenAddress The token used for entry (address(0) if ether)
 @param _toTokenAddress The intermediate ERC20 token to swap to
 @param _swapAddress Curve swap address for the pool
 @param _incomingTokenQty The amount of fromToken to invest
 @param _minPoolTokens The minimum acceptable quantity of Curve LP to receive. Reverts otherwise
 @param _swapTarget Excecution target for the first swap
 @param _swapCallData DEX quote data
 @param affiliate Affiliate address
 @return crvTokensBought- Quantity of Curve LP tokens received
 */
function ZapIn(
        address _fromTokenAddress,
        address _toTokenAddress,
        address _swapAddress,
        uint256 _incomingTokenQty,
        uint256 _minPoolTokens,
        address _swapTarget,
        bytes calldata _swapCallData,
        address affiliate
    ) external payable stopInEmergency returns (uint256 crvTokensBought) {
        uint256 toInvest = _pullTokens(
            _fromTokenAddress,
            _incomingTokenQty,
            affiliate
        );
        if (_fromTokenAddress == address(0)) {
            _fromTokenAddress = ETHAddress;
        }

        // perform zapIn
        crvTokensBought = _performZapIn(
            _fromTokenAddress,
            _toTokenAddress,
            _swapAddress,
            toInvest,
            _swapTarget,
            _swapCallData
        );

        require(
            crvTokensBought > _minPoolTokens,
            "Received less than minPoolTokens"
        );

        address poolTokenAddress = curveReg.getTokenAddress(_swapAddress);

        emit zapIn(msg.sender, poolTokenAddress, crvTokensBought);

        IERC20(poolTokenAddress).transfer(msg.sender, crvTokensBought);
    }
// Solidity 0.5.17
/**
 @notice This function gets adds the liquidity for meta pools and returns the token index and swap tokens
 @param _swapAddress Curve swap address for the pool
 @param _toTokenAddress The ERC20 token to which from token to be convert
 @param  swapTokens amount of toTokens to invest
 @return tokensBought- quantity of curve LP acquired
 @return index- index of LP token in _swapAddress whose pool tokens were acquired
 */
function _enterMetaPool(
        address _swapAddress,
        address _toTokenAddress,
        uint256 swapTokens
    ) internal returns (uint256 tokensBought, uint8 index) {
        address[4] memory poolTokens = curveReg.getPoolTokens(_swapAddress);
        for (uint8 i = 0; i < 4; i++) {
            address intermediateSwapAddress = curveReg.getSwapAddress(
                poolTokens[i]
            );
            if (intermediateSwapAddress != address(0)) {
                (, index) = curveReg.isUnderlyingToken(
                    intermediateSwapAddress,
                    _toTokenAddress
                );

                tokensBought = _enterCurve(
                    intermediateSwapAddress,
                    swapTokens,
                    index
                );

                return (tokensBought, i);
            }
        }
    }
// Solidity 0.5.17
/**
 @notice This function adds liquidity to a curve pool
 @param _swapAddress Curve swap address for the pool
 @param amount The quantity of tokens being added as liquidity
 @param index The token index for the add_liquidity call
 @return crvTokensBought- the quantity of curve LP tokens received
 */
function _enterCurve(
        address _swapAddress,
        uint256 amount,
        uint8 index
    ) internal returns (uint256 crvTokensBought) {
        address tokenAddress = curveReg.getTokenAddress(_swapAddress);
        address depositAddress = curveReg.getDepositAddress(_swapAddress);
        uint256 initialBalance = IERC20(tokenAddress).balanceOf(address(this));
        address entryToken = curveReg.getPoolTokens(_swapAddress)[index];
        if (entryToken != ETHAddress) {
            IERC20(entryToken).safeIncreaseAllowance(
                address(depositAddress),
                amount
            );
        }

        uint256 numTokens = curveReg.getNumTokens(_swapAddress);
        bool addUnderlying = curveReg.shouldAddUnderlying(_swapAddress);

        if (numTokens == 4) {
            uint256[4] memory amounts;
            amounts[index] = amount;
            if (addUnderlying) {
                ICurveSwap(depositAddress).add_liquidity(amounts, 0, true);
            } else {
                ICurveSwap(depositAddress).add_liquidity(amounts, 0);
            }
        } else if (numTokens == 3) {
            uint256[3] memory amounts;
            amounts[index] = amount;
            if (addUnderlying) {
                ICurveSwap(depositAddress).add_liquidity(amounts, 0, true);
            } else {
                ICurveSwap(depositAddress).add_liquidity(amounts, 0);
            }
        } else {
            uint256[2] memory amounts;
            amounts[index] = amount;
            if (curveReg.isEthPool(depositAddress)) {
                ICurveEthSwap(depositAddress).add_liquidity.value(amount)(
                    amounts,
                    0
                );
            } else if (addUnderlying) {
                ICurveSwap(depositAddress).add_liquidity(amounts, 0, true);
            } else {
                ICurveSwap(depositAddress).add_liquidity(amounts, 0);
            }
        }
        crvTokensBought = (IERC20(tokenAddress).balanceOf(address(this))).sub(
            initialBalance
        );
    }
// Solidity 0.4.24
// base rate is 100, so for 1 to 1 send in 100 as ratio
function addMiningToken(address tokenAddr, uint ratio) onlyAdmin external {
    require(exchangeRatios[tokenAddr] == 0 && ratio > 0 && ratio < 10000);
    exchangeRatios[tokenAddr] = ratio;

    bool found = false;
    for (uint16 i = 0; i < miningTokens.length; i++) {
      if (miningTokens[i] == tokenAddr) {
        found = true;
        break;
      }
    }
    if (!found) {
      miningTokens.push(tokenAddr);
    }
    emit MiningTokenAdded(tokenAddr, ratio);
  }
// Solidity 0.4.19
// This function is called at the time of contract creation,
// it sets the initial variables and whitelists the contract owner.
function PresalePool (address receiverAddr, uint contractCap, uint cap, uint fee) public {
    require (fee < 100);
    require (contractCap >= cap);
    owner = msg.sender;
    receiverAddress = receiverAddr;
    maxContractBalance = contractCap;
    contributionCap = cap;
    feePct = _toPct(fee,100);
  }
// Solidity 0.4.19
// Internal function for handling eth deposits during contract stage one.
function _ethDeposit () internal {
    assert (contractStage == 1);
    require (!whitelistIsActive || whitelistContract.isPaidUntil(msg.sender) > now);
    require (tx.gasprice <= maxGasPrice);
    require (this.balance <= maxContractBalance);
    var c = whitelist[msg.sender];
    uint newBalance = c.balance.add(msg.value);
    require (newBalance >= contributionMin);
    if (nextCapTime > 0 && nextCapTime < now) {
      contributionCap = nextContributionCap;
      nextCapTime = 0;
    }
    if (c.cap > 0) require (newBalance <= c.cap);
    else require (newBalance <= contributionCap);
    c.balance = newBalance;
    ContributorBalanceChanged(msg.sender, newBalance);
  }
// Solidity 0.4.19
// This function is called to withdraw eth or tokens from the contract.
// It can only be called by addresses that are whitelisted and show a balance greater than 0.
// If called during stage one, the full eth balance deposited into the contract is returned and the contributor's balance reset to 0.
// If called during stage two, the contributor's unused eth will be returned, as well as any available tokens.
// The token address may be provided optionally to withdraw tokens that are not currently the default token (airdrops).
function withdraw (address tokenAddr) public {
    var c = whitelist[msg.sender];
    require (c.balance > 0);
    if (contractStage == 1) {
      uint amountToTransfer = c.balance;
      c.balance = 0;
      msg.sender.transfer(amountToTransfer);
      ContributorBalanceChanged(msg.sender, 0);
    } else {
      _withdraw(msg.sender,tokenAddr);
    }  
  }
// Solidity 0.4.19
// This internal function handles withdrawals during stage two.
// The associated events will fire to notify when a refund or token allocation is claimed.
function _withdraw (address receiver, address tokenAddr) internal {
    assert (contractStage == 2);
    var c = whitelist[receiver];
    if (tokenAddr == 0x00) {
      tokenAddr = activeToken;
    }
    var d = distributionMap[tokenAddr];
    require ( (ethRefundAmount.length > c.ethRefund) || d.pct.length > c.tokensClaimed[tokenAddr] );
    if (ethRefundAmount.length > c.ethRefund) {
      uint pct = _toPct(c.balance,finalBalance);
      uint ethAmount = 0;
      for (uint i=c.ethRefund; i<ethRefundAmount.length; i++) {
        ethAmount = ethAmount.add(_applyPct(ethRefundAmount[i],pct));
      }
      c.ethRefund = ethRefundAmount.length;
      if (ethAmount > 0) {
        receiver.transfer(ethAmount);
        EthRefunded(receiver,ethAmount);
      }
    }
    if (d.pct.length > c.tokensClaimed[tokenAddr]) {
      uint tokenAmount = 0;
      for (i=c.tokensClaimed[tokenAddr]; i<d.pct.length; i++) {
        tokenAmount = tokenAmount.add(_applyPct(c.balance,d.pct[i]));
      }
      c.tokensClaimed[tokenAddr] = d.pct.length;
      if (tokenAmount > 0) {
        require(d.token.transfer(receiver,tokenAmount));
        d.balanceRemaining = d.balanceRemaining.sub(tokenAmount);
        TokensWithdrawn(receiver,tokenAddr,tokenAmount);
      }  
    }
    
  }
// Solidity 0.4.19
// This function is called by the owner to modify the cap at a future time.
function modifyNextCap (uint time, uint cap) public onlyOwner {
    require (contractStage == 1);
    require (contributionCap <= cap && maxContractBalance >= cap);
    require (time > now);
    nextCapTime = time;
    nextContributionCap = cap;
  }
// Solidity 0.4.19
// This callable function returns the total pool cap, current balance and remaining balance to be filled.
function checkPoolBalance () view public returns (uint poolCap, uint balance, uint remaining) {
    if (contractStage == 1) {
      remaining = maxContractBalance.sub(this.balance);
    } else {
      remaining = 0;
    }
    return (maxContractBalance,this.balance,remaining);
  }
// Solidity 0.4.19
// This callable function returns the balance, contribution cap, and remaining available balance of any contributor.
function checkContributorBalance (address addr) view public returns (uint balance, uint cap, uint remaining) {
    var c = whitelist[addr];
    if (contractStage == 2) return (c.balance,0,0);
    if (whitelistIsActive && whitelistContract.isPaidUntil(addr) < now) return (c.balance,0,0);
    if (c.cap > 0) cap = c.cap;
    else cap = contributionCap;
    if (cap.sub(c.balance) > maxContractBalance.sub(this.balance)) return (c.balance, cap, maxContractBalance.sub(this.balance));
    return (c.balance, cap, cap.sub(c.balance));
  }
// Solidity 0.4.19
// This callable function returns the token balance that a contributor can currently claim.
function checkAvailableTokens (address addr, address tokenAddr) view public returns (uint tokenAmount) {
    var c = whitelist[addr];
    var d = distributionMap[tokenAddr];
    for (uint i = c.tokensClaimed[tokenAddr]; i < d.pct.length; i++) {
      tokenAmount = tokenAmount.add(_applyPct(c.balance, d.pct[i]));
    }
    return tokenAmount;
  }
// Solidity 0.4.19
// This function sends the pooled eth to the receiving address, calculates the % of unused eth to be returned,
// and advances the contract to stage two. It can only be called by the contract owner during stages one or two.
// The amount to send (given in wei) must be specified during the call. As this function can only be executed once,
// it is VERY IMPORTANT not to get the amount wrong.
function submitPool (uint amountInWei) public onlyOwner noReentrancy {
    require (contractStage == 1);
    require (receiverAddress != 0x00);
    require (block.number >= addressChangeBlock.add(6000));
    if (amountInWei == 0) amountInWei = this.balance;
    require (contributionMin <= amountInWei && amountInWei <= this.balance);
    finalBalance = this.balance;
    require (receiverAddress.call.value(amountInWei).gas(msg.gas.sub(5000))());
    if (this.balance > 0) ethRefundAmount.push(this.balance);
    contractStage = 2;
    PoolSubmitted(receiverAddress, amountInWei);
  }
// Solidity 0.4.19
// This function opens the contract up for token withdrawals.
// It can only be called by the owner during stage two.  The owner specifies the address of an ERC20 token
// contract that this contract has a balance in, and optionally a bool to prevent this token from being
// the default withdrawal (in the event of an airdrop, for example).
function enableTokenWithdrawals (address tokenAddr, bool notDefault) public onlyOwner noReentrancy {
    require (contractStage == 2);
    if (notDefault) {
      require (activeToken != 0x00);
    } else {
      activeToken = tokenAddr;
    }
    var d = distributionMap[tokenAddr];    
    if (d.pct.length==0) d.token = ERC20(tokenAddr);
    uint amount = d.token.balanceOf(this).sub(d.balanceRemaining);
    require (amount > 0);
    if (feePct > 0) {
      require (d.token.transfer(owner,_applyPct(amount,feePct)));
    }
    amount = d.token.balanceOf(this).sub(d.balanceRemaining);
    d.balanceRemaining = d.token.balanceOf(this);
    d.pct.push(_toPct(amount,finalBalance));
  }
// Solidity 0.6.12
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
 * the total supply.
 *
 * Emits a {Transfer} event with `from` set to the zero address.
 *
 * Requirements
 *
 * - `to` cannot be the zero address.
 * 
 * HINT: This function is 'internal' and therefore can only be called from another
 * function inside this contract!
 */
function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");
        _beforeTokenTransfer(address(0), account, amount);
        _totalSupply = _totalSupply.add(amount);
        _balances[account] = _balances[account].add(amount);
        emit Transfer(address(0), account, amount);
    }
// Solidity 0.4.24
/**
 @dev Inserts a new node between _prev and _next. When inserting a node already existing in 
 the list it will be automatically removed from the old position.
 @param _prev the node which _new will be inserted after
 @param _curr the id of the new node being inserted
 @param _next the node which _new will be inserted before
 */
function insert(Data storage self, uint _prev, uint _curr, uint _next) public {
    require(_curr != NULL_NODE_ID);

    remove(self, _curr);

    require(_prev == NULL_NODE_ID || contains(self, _prev));
    require(_next == NULL_NODE_ID || contains(self, _next));

    require(getNext(self, _prev) == _next);
    require(getPrev(self, _next) == _prev);

    self.dll[_curr].prev = _prev;
    self.dll[_curr].next = _next;

    self.dll[_prev].next = _curr;
    self.dll[_next].prev = _curr;
  }
// Solidity 0.4.24
/**
 @notice Commits vote using hash of choice and secret salt to conceal vote until reveal
 @param _pollID Integer identifier associated with target poll
 @param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order)
 @param _numTokens The number of tokens to be committed towards the target poll
 @param _prevPollID The ID of the poll that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
 */
function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public {
        require(commitPeriodActive(_pollID));

        // if msg.sender doesn't have enough voting rights,
        // request for enough voting rights
        if (voteTokenBalance[msg.sender] < _numTokens) {
            uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]);
            requestVotingRights(remainder);
        }

        // make sure msg.sender has enough voting rights
        require(voteTokenBalance[msg.sender] >= _numTokens);
        // prevent user from committing to zero node placeholder
        require(_pollID != 0);
        // prevent user from committing a secretHash of 0
        require(_secretHash != 0);

        // Check if _prevPollID exists in the user's DLL or if _prevPollID is 0
        require(_prevPollID == 0 || dllMap[msg.sender].contains(_prevPollID));

        uint nextPollID = dllMap[msg.sender].getNext(_prevPollID);

        // edge case: in-place update
        if (nextPollID == _pollID) {
            nextPollID = dllMap[msg.sender].getNext(_pollID);
        }

        require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens));
        dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID);

        bytes32 UUID = attrUUID(msg.sender, _pollID);

        store.setAttribute(UUID, "numTokens", _numTokens);
        store.setAttribute(UUID, "commitHash", uint(_secretHash));

        pollMap[_pollID].didCommit[msg.sender] = true;
        emit _VoteCommitted(_pollID, _numTokens, msg.sender);
    }
// Solidity 0.4.24
/**
 @notice                 Commits votes using hashes of choices and secret salts to conceal votes until reveal
 @param _pollIDs         Array of integer identifiers associated with target polls
 @param _secretHashes    Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order)
 @param _numsTokens      Array of numbers of tokens to be committed towards the target polls
 @param _prevPollIDs     Array of IDs of the polls that the user has voted the maximum number of tokens in which is still less than or equal to numTokens
 */
function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external {
        // make sure the array lengths are all the same
        require(_pollIDs.length == _secretHashes.length);
        require(_pollIDs.length == _numsTokens.length);
        require(_pollIDs.length == _prevPollIDs.length);

        // loop through arrays, committing each individual vote values
        for (uint i = 0; i < _pollIDs.length; i++) {
            commitVote(_pollIDs[i], _secretHashes[i], _numsTokens[i], _prevPollIDs[i]);
        }
    }
// Solidity 0.4.24
/**
 @dev Compares previous and next poll's committed tokens for sorting purposes
 @param _prevID Integer identifier associated with previous poll in sorted order
 @param _nextID Integer identifier associated with next poll in sorted order
 @param _voter Address of user to check DLL position for
 @param _numTokens The number of tokens to be committed towards the poll (used for sorting)
 @return valid Boolean indication of if the specified position maintains the sort
 */
function validPosition(uint _prevID, uint _nextID, address _voter, uint _numTokens) public constant returns (bool valid) {
        bool prevValid = (_numTokens >= getNumTokens(_voter, _prevID));
        // if next is zero node, _numTokens does not need to be greater
        bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0);
        return prevValid && nextValid;
    }