# RACE #16 - Flash Loan

{% embed url="<https://ventral.digital/posts/2023/4/1/race-16-of-the-secureum-bootcamp-epoch-infinity>" %}
RACE #16
{% endembed %}

<figure><img src="https://3988450783-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MWVjG_njKgBtvmnKaJh%2Fuploads%2FRKmXJts4CmnXArgFMvzs%2Fimage.png?alt=media&#x26;token=bf98f711-6750-4453-9032-c987f3a78f10" alt=""><figcaption><p>RACE #16 result</p></figcaption></figure>

{% hint style="info" %}
*Note: All 8 questions in this RACE are based on the below contract. This is the same contract you will see for all the 8 questions in this RACE. The question is below the shown contract.*
{% endhint %}

```solidity
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;


import "@openzeppelin/contracts/interfaces/IERC3156FlashLender.sol";
import "@openzeppelin/contracts/interfaces/IERC20.sol";


contract FlashLoan is IERC3156FlashLender {
   bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan");
   uint256 public fee;


   /**
    * @param fee_ the fee that should be paid on a flashloan
    */
   constructor (
       uint256 fee_
   ) {
       fee = fee_;
   }


   /**
    * @dev The amount of currency available to be lent.
    * @param token The loan currency.
    * @return The amount of `token` that can be borrowed.
    */
   function maxFlashLoan(
       address token
   ) public view override returns (uint256) {
       return IERC20(token).balanceOf(address(this));
   }


   /**
    * @dev The fee to be charged for a given loan.
    * @param token The loan currency. Must match the address of this contract.
    * @param amount The amount of tokens lent.
    * @return The amount of `token` to be charged for the loan, on top of the returned principal.
    */
   function flashFee(
       address token,
       uint256 amount
   ) external view override returns (uint256) {
       return fee;
   }


   /**
    * @dev Loan `amount` tokens to `receiver`, and takes it back plus a `flashFee` after the ERC3156 callback.
    * @param receiver The contract receiving the tokens, needs to implement the `onFlashLoan(address user, uint256 amount, uint256 fee, bytes calldata)` interface.
    * @param token The loan currency. Must match the address of this contract.
    * @param amount The amount of tokens lent.
    * @param data A data parameter to be passed on to the `receiver` for any custom use.
    */
   function flashLoan(
       IERC3156FlashBorrower receiver,
       address token,
       uint256 amount,
       bytes calldata data
   ) external override returns (bool){
       uint256 oldAllowance = IERC20(token).allowance(address(this), address(receiver));
       uint256 oldBal = IERC20(token).balanceOf(address(this));
       require(amount <= oldBal, "Too many funds requested");
       IERC20(token).approve(address(receiver), oldAllowance + amount);

       require(
           receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS,
           "Callback failed"
       );

       uint256 newBal = IERC20(token).balanceOf(address(this));
       if(newBal < oldBal + fee) {
           uint retAmt = oldBal + fee - newBal;
           require(IERC20(token).transferFrom(msg.sender, address(this), retAmt), "All funds not returned");
       }

       if (IERC20(token).allowance(address(this), address(receiver)) > oldAllowance) {
           IERC20(token).approve(address(receiver), oldAllowance);
       }

       return true;
   }
}
```

## Question 1 :white\_check\_mark:

Which of the following is an explanation of why *flashLoan()* could revert?

* [x] &#x20;A. The transaction reverts because a user requested to borrow more than *maxFlashLoan() ->* `require(amount <= oldBal, "Too many funds requested");`
* [x] &#x20;B. The transaction reverts because the receiver’s *onFlashLoan()* did not return *CALLBACK\_SUCCESS ->* `receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS`
* [ ] &#x20;C. The transaction reverts because the user returned more than *retAmt* funds -> Nothing stops user from returning more fund.
* [x] &#x20;D. The transaction reverts because a user tried to spend more funds than their allowance in *onFlashLoan() ->* `receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS`

## Question 2 :white\_check\_mark:

If the *FlashLoan* contract were safe, which of the following invariants should hold at the end of any given transaction for some ERC20 token *t*? Note: `old(expr)` evaluates expr at the beginning of the transaction.

* [x] &#x20;A. t.balanceOf(address(this)) >= old(t.balanceOf(address(this)))
* [ ] &#x20;B. t.balanceOf(address(this)) == old(t.balanceOf(address(this)))
* [ ] &#x20;C. t.balanceOf(address(this)) > old(t.balanceOf(address(this)))
* [ ] &#x20;D. t.balanceOf(address(this)) == old(t.balanceOf(address(this))) + fee

**Comment:**

For the flashloan to be safe, the contract's token balance must be maintained no matter which function is called. It must be (A) because flashloan will cause the token balance to either increase or stay the same (depending on fee) and all other functions should maintain token balances

## Question 3 :white\_check\_mark:

Which of the following tokens would be unsafe for the above contract to loan as doing so could result in theft?

* [ ] &#x20;A. ERC223
* [ ] &#x20;B. ERC677
* [x] &#x20;C. ERC777 -> It has the `transferFrom()` callback
* [ ] &#x20;D. ERC1155 -> It has callback but does not have `transferFrom()`, therefore will revert

## Question 4 :white\_check\_mark:

Which external call made by *flashLoan()* could result in theft if the token(s) identified in the previous question were to be used?

* [ ] &#x20;A. *onFlashLoan()*
* [ ] &#x20;B. *balanceOf()*
* [x] &#x20;C. *transferFrom() ->* ERC777 `transferFrom()` has callback
* [ ] &#x20;D. *approve()*

## Question 5 :white\_check\_mark:

What is the purpose of the fee in the *FlashLoan* contract as is?

* [x] &#x20;A. To increase the size of available flashloans over time
* [ ] &#x20;B. To pay the owner of the flashloan contract
* [ ] &#x20;C. To pay those who staked their funds to be flashloaned
* [ ] &#x20;D. It has no purpose

**Comment:**

In the current *FlashLoan* contract, as it is, the sole purpose of the fee is to increase the available funds to loan.

## Question 6 :white\_check\_mark:

Which of the following describes the behavior of *maxFlashLoan* for a standard ERC20 token over time?

* [ ] &#x20;A. strictly-increasing
* [x] &#x20;B. non-decreasing
* [ ] &#x20;C. constant
* [ ] &#x20;D. None of the above

## Question 7 - This one tricky

For some arbitrary ERC20 token *t*, which of the following accurately describes the *FlashLoan* contract’s balance of *t* after a successful (i.e. non-reverting) call to *flashLoan()* (where *t* is the token requested for the flashloan):

* [ ] &#x20;A. The *FlashLoan* contract's balance of token *t* will INCREASE OR STAY THE SAME.
* [ ] &#x20;B. The *FlashLoan* contract's balance of token *t* will DECREASE OR STAY THE SAME.
* [ ] &#x20;C. The *FlashLoan* contract's balance of token *t* will STAY THE SAME.
* [x] &#x20;D. None of the above.

**Comment:**

*flashLoan()* can hypothetically finish successfully with any token that implements the ERC20 interface, <mark style="color:red;">**even if it is a bogus implementation**</mark>. Therefore, there are no guarantees on the output of *IERC20(token).balanceOf(user).*

## Question 8 :white\_check\_mark:

Which of the following are guaranteed to hold after a successful (i.e., non-reverting) execution of *flashLoan()*, assuming the token for which the flashloan is requested uses OpenZeppelin’s Standard ERC20 implementation?

* [ ] &#x20;A. The receiver’s balance of “token” increases -> if I set `amount = 0`, receiver's balance would decrease because of the fee
* [x] &#x20;B. The funds that the *FlashLoan* contract has approved the receiver to spend has either stayed the same or decreased. -> the last if statement ensures allowance is non-increasing
* [ ] &#x20;C. The sum of all flashloans granted by the *FlashLoan* contract is less than the *maxFlashLoan* amount. -> maxFlashLoan is the upper bound of a single flashloan
* [ ] &#x20;D. The token balance of any contract/user other than the *FlashLoan* contract, the caller of the *flashLoan()*, and the “receiver” contract will remain the same as before the call to *flashLoan()*. -> onFlashLoan() might change those balances
