EIPs/EIPS/eip-3156.md
Alberto Cuesta Cañada c949c89665
erc-3156 ready for review (#3181)
This ERC provides standard interfaces and processes for flash lenders and borrowers, allowing for flash loan integration without a need to consider each particular implementation.
2021-01-15 11:50:45 +08:00

463 lines
21 KiB
Markdown

---
eip: 3156
title: Flash Loans
author: Alberto Cuesta Cañada (@albertocuestacanada), Fiona Kobayashi (@fifikobayashi), fubuloubu (@fubuloubu), Austin Williams (@onewayfunction)
discussions-to: https://ethereum-magicians.org/t/erc-3156-flash-loans-review-discussion/5077
status: Review
type: Standards Track
category: ERC
created: 2020-11-15
---
## Simple Summary
This ERC provides standard interfaces and processes for flash lenders and borrowers, allowing for flash loan integration without a need to consider each particular implementation.
## Motivation
Flash loans allow smart contracts to lend an amount of tokens without a requirement for collateral, with the condition that they must be returned within the same transaction.
Early adopters of the flash loan pattern, such as [Aave](https://github.com/aave/aave-protocol/blob/e8d020e9752fbd4807a3b55f9cf98a88dcfb674d/contracts/flashloan), [DxDy](https://help.dydx.exchange/en/articles/3724602-flash-loans), [Uniswap](https://uniswap.org/docs/v2/core-concepts/flash-swaps/) and the [Yield Protocol](https://github.com/yieldprotocol/fyDai/blob/master/contracts/FYDai.sol) have produced different interfaces and different use patterns. The diversification is expected to intensify, and with it the technical debt required to integrate with diverse flash lending patterns.
Some of the high level diferences in the approaches across the protocols include:
- Repayment approaches at the end of the transaction, where Aave V2 pulls the flash loaned amount plus the flash fee off the flash smart contract, compared to other protocols where the contract needs to explicitly calculate the debt+fee amount and manually return it to the lending pool.
- Uniswap's Flash Swaps offer the ability to repay the flash transaction using a token that is different to what was originally flash borrowed, which can reduce the overall complexity of the flash transaction and gas fees, depending on the purpose of the flash swap (i.e. the second last step in flash self liquidation to swap back into the repayment token).
- DyDx offering a single entry point into the protocol regardless of whether you're buying, selling, depositing or chaining them together as a flash loan, whereas other protocols offer discrete entry points (e.g. Uniswap V2's swap() and Aave V2's flashLoan() methods).
- The Yield Protocol allows to flash mint any amount of its native token without charging a fee, effectively allowing flash loans bounded by computational constraints instead of asset ownership constraints.
## Specification
A flash lending feature integrates two smart contracts using a callback pattern. These are called the LENDER and the RECEIVER in this EIP.
### Lender Specification
A `lender` MUST implement the IERC3156FlashLender interface.
```
interface IERC3156FlashLender {
function maxFlashAmount(
IERC20 token
) external view returns (uint256);
function flashFee(
IERC20 token,
uint256 amount
) external view returns (uint256);
function flashLoan(
IERC3156FlashBorrower receiver,
IERC20 token,
uint256 amount,
bytes calldata data
) external;
}
```
The `maxFlashAmount` function MUST return the maximum loan possible for `token`. If a `token` is not currently supported `maxFlashAmount` MUST return 0, instead of reverting.
The `flashFee` function MUST return the fee charged for a loan of `amount` `token`. If the loan cannot be executed `flashFee` MUST revert.
The `flashLoan` function MUST include a callback to the `onFlashLoan` function in a `IERC3156FlashBorrower` contract.
```
function flashLoan(
IERC3156FlashBorrower receiver,
IERC20 token,
uint256 amount,
bytes calldata data
) external {
...
receiver.onFlashLoan(msg.sender, token, amount, fee, data);
...
}
```
The `flashLoan` function MUST transfer `amount` of `token` to `receiver` before the callback to the borrower.
The `flashLoan` function MUST include `msg.sender` as the `sender` to `onFlashLoan`.
The `flashLoan` function MUST NOT modify the `token`, `amount` and `data` parameter received, and MUST pass them on to `onFlashLoan`.
After the callback, the `flashLoan` function MUST take the `amount + fee` `token` from the `receiver`, or revert if this is not successful.
The *batch flash loans* extension is OPTIONAL for ERC-3156 smart contracts. This allows flash loans to be composed of several ERC20 tokens.
A `lender` offering batch flash loans MUST implement the IERC3156BatchFlashLender interface.
```
interface IERC3156BatchFlashLender is IERC3156FlashLender {
function batchFlashLoan(
IERC3156BatchFlashBorrower receiver,
IERC20[] tokens,
uint256[] amounts,
bytes calldata data
) external;
}
```
The `batchFlashLoan` function MUST revert if the length of the `amounts` and `tokens` arrays differ.
The `batchFlashLoan` function MUST include a callback to the `onBatchFlashLoan` function in a `IERC3156BatchFlashBorrower` contract.
```
function batchFlashLoan(
IERC3156BatchFlashBorrower receiver,
IERC20[] calldata token,
uint256[] calldata amount,
bytes calldata data
) external {
...
receiver.onBatchFlashLoan(msg.sender, tokens, amounts, fees, data);
...
}
```
For each `token` in `tokens`, the `batchFlashLoan` function MUST transfer `amounts[i]` of `tokens[i]` to `receiver` before the callback to the borrower.
The `batchFlashLoan` function MUST include `msg.sender` as the `sender` to `onBatchFlashLoan`.
The `batchFlashLoan` function MUST include a `fees` argument to `onBatchFlashLoan` with the fee to pay for each individual `token` and `amount` lent.
The `batchFlashLoan` function MUST NOT modify the `tokens`, `amounts` and `data` parameters received, and MUST pass them on to `onBatchFlashLoan`.
After the callback, for each `token` in `tokens`, the `batchFlashLoan` function MUST take the `amounts[i] + fees[i]` of `tokens[i]` from the `receiver`, or revert if this is not successful.
### Receiver Specification
A `receiver` of flash loans MUST implement the IERC3156FlashBorrower interface with an `onFlashLoan` callback:
```
interface IERC3156FlashBorrower {
function onFlashLoan(
IERC3156FlashLender sender,
IERC20 token,
uint256 amount,
uint256 fee,
bytes calldata data
) external;
}
```
For the transaction to not revert, `receiver` MUST approve `amount + fee` of `token` to be taken by `msg.sender` before the end of `onFlashLoan`.
The *batch flash loans* extension is OPTIONAL for ERC-3156 smart contracts. This allows flash loans to be composed of several ERC20 tokens.
```
interface IERC3156BatchFlashBorrower {
function onBatchFlashLoan(
IERC3156BatchFlashLender sender,
IERC20[] calldata tokens,
uint256[] calldata amounts,
uint256[] calldata fees,
bytes calldata data
) external;
}
```
For the transaction to not revert, for each `token` in `tokens`, `receiver` MUST approve `amounts[i] + fees[i]` of `tokens[i]` to be taken by `msg.sender` before the end of `onFlashLoan`.
## Rationale
The interfaces described in this ERC have been chosen as to cover the known flash lending use cases, while allowing for safe and gas efficient implementations.
`flashFee(address token, uint256 amount)`
`flashFee` reverts on unsupported tokens, because returning a numerical value would be incorrect.
`flashLoan(address receiver, address token, uint256 amount, bytes calldata data)`
`flashLoan` has been chosen as descriptive enough, unlikely to clash with other functions in the lender, and including both the use cases in which the tokens lended are held or minted by the lender.
`receiver` is taken as a parameter to allow flexibility on the implementation of separate loan initiators and receivers.
Existing flash lenders (Aave, dYdX and Uniswap) all provide flash loans of several token types from the same contract (LendingPool, SoloMargin and UniswapV2Pair). Providing a `token` parameter in both the `flashLoan` and `onFlashLoan` functions matches closely the observed functionality.
A `bytes calldata data` parameter is included for the caller to pass arbitrary information to the `receiver`, without impacting the utility of the `flashLoan` standard.
`onFlashLoan(msg.sender, amount, fee, data)`
`onFlashLoan` has been chosen as descriptive enough, unlikely to clash with other functions in the `receiver`, and following the `onAction` naming pattern used as well in EIP-667.
A `sender` will often be required in the `onFlashLoan` function, which the lender knows as `msg.sender`. An alternative implementation which would embed the `sender` in the `data` parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable.
The `amount` will be required in the `onFlashLoan` function, which the lender took as a parameter. An alternative implementation which would embed the `amount` in the `data` parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable.
A `fee` will often be calculated in the `flashLoan` function, which the `receiver` must be aware of for repayment. Passing the `fee` as a parameter instead of appended to `data` is simple and effective.
The `amount + fee` are pulled from the `receiver` to allow the `lender` to implement other functionality that depend on `token` balances, without having to lock it for the duration of a flash loan.
## Backwards Compatibility
No backwards compatibility issues identified.
## Implementation
### Flash Borrower Reference Implementation
```
pragma solidity ^0.8.0;
import "../interfaces/IERC20.sol";
contract FlashBorrower {
function flashBorrow(IERC3156FlashLender lender, IERC20 token, uint256 amount) public {
uint256 _allowance = token.allowance(address(this), lender);
uint256 _fee = lender.flashFee(token, amount);
uint256 _repayment = amount + _fee;
token.approve(lender, _allowance + _repayment);
lender.flashLoan(this, token, amount, data);
}
}
```
### Flash Mint Reference Implementation
```
pragma solidity ^0.8.0;
import "./ERC20.sol";
import "../interfaces/IERC3156FlashBorrower.sol";
import "../interfaces/IERC3156FlashLender.sol";
/**
* @author Alberto Cuesta Cañada
* @dev Extension of {ERC20} that allows flash minting.
*/
contract FlashMinter is ERC20, IERC3156FlashLender {
uint256 public fee; // Percentage charged on the amount, in bps
/**
* @param fee_ The divisor that will be applied to the `amount` of a `loan`, with the result charged as a `fee`.
*/
constructor (
string memory name,
string memory symbol,
uint256 fee_
) ERC20(name, symbol) {
fee = fee_;
}
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashAmount(
IERC20
) external view override returns (uint256) {
return type(uint256).max;
}
/**
* @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(
IERC20 token,
uint256 amount
) external view override returns (uint256) {
require(
token == this,
"FlashMinter: unsupported loan currency"
);
return _flashFee(token, amount);
}
/**
* @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 data)` 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,
IERC20 token,
uint256 amount,
bytes calldata data
) external override {
require(token == this, "FlashMinter: unsupported loan currency");
uint256 fee = _flashFee(token, amount);
_mint(address(receiver), amount);
receiver.onFlashLoan(msg.sender, token, amount, fee, data);
uint256 _allowance = allowance(address(receiver), address(this));
require(_allowance >= (amount + fee), "FlashMinter: Flash loan repayment not approved");
_approve(address(receiver), address(this), _allowance - (amount + fee));
_burn(address(receiver), amount + fee);
}
/**
* @dev The fee to be charged for a given loan. Internal function with no checks.
* @param token The loan currency.
* @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(
IERC20,
uint256 amount
) internal view returns (uint256) {
return fee == amount * fee / 10000;
}
```
### Flash Loan Reference Implementation
```
pragma solidity ^0.8.0;
import "../interfaces/IERC20.sol";
import "../interfaces/IERC3156FlashBorrower.sol";
import "../interfaces/IERC3156FlashLender.sol";
/**
* @author Alberto Cuesta Cañada
* @dev Contract that allows flash lending of any ERC20 tokens it owns.
*/
contract FlashLender is IERC3156FlashLender {
mapping(IERC20 => bool) public supportedTokens;
uint256 public fee; // Percentage charged on the amount, in bps
/**
* @param supportedTokens_ Token contracts supported for flash lending.
* @param fee_ The divisor that will be applied to the `amount` of a `loan`, with the result charged as a `fee`.
*/
constructor(
IERC20[] memory supportedTokens_,
uint256 fee_)
{
for (uint256 i = 0; i < supportedTokens_.length; i++) {
supportedTokens[supportedTokens_[i]] = true;
}
fee = fee_;
}
/**
* @dev Loan `amount` tokens to `receiver`, and takes it back plus a `flashFee` after the callback.
* @param receiver The contract receiving the tokens, needs to implement the IERC3156FlashBorrower interface.
* @param token The loan currency.
* @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,
IERC20 token,
uint256 amount,
bytes calldata data
) external override {
require(
supportedTokens[token],
"FlashLender: Unsupported currency"
);
uint256 fee = _flashFee(token, amount);
require(
token.transfer(address(receiver), amount),
"FlashLender: Transfer failed"
);
receiver.onFlashLoan(msg.sender, token, amount, fee, data);
require(
token.transferFrom(address(receiver), address(this), amount + fee),
"FlashLender: Repay failed"
);
}
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @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(
IERC20 token,
uint256 amount
) external view override returns (uint256) {
require(supportedTokens[token], "FlashLender: Unsupported currency");
return _flashFee(token, amount);
}
/**
* @dev The fee to be charged for a given loan. Internal function with no checks.
* @param token The loan currency.
* @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(
IERC20 token,
uint256 amount
) internal view returns (uint256) {
return amount * fee / 10000;
}
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashAmount(
IERC20 token
) external view override returns (uint256) {
return supportedTokens[address(token)] ? token.balanceOf(address(this)) : 0;
}
}
```
## Security Considerations
### Verification of callback arguments
The arguments of `onFlashLoan` are expected to reflect the conditions of the flash loan, but cannot be trusted unconditionally. They can be divided in two groups, that require different checks before they can be trusted to be genuine.
0. No arguments can be assumed to be genuine without some kind of verification. `sender`, `token` and `value` refer to a past transaction that might not have happened if the caller of `onFlashLoan` decides to lie. `fee` might be false or calculated incorrectly. `data` might have been manipulated by the caller.
1. To trust that the value of `sender`, `token`, `value` and `fee` are genuine a reasonable pattern is to verify that the `onFlashLoan` caller is in a whitelist of verified flash lenders. Since often the caller of `flashLoan` will also be receiving the `onFlashLoan` callback this will be trivial. In all other cases flash lenders will need to be approved if the arguments in `onFlashLoan` are to be trusted.
2. To trust that the value of `data` is genuine, in addition to the check in point 1, it is recommended to implement the `flashLoan` caller to be also the `onFlashLoan` receiver. With this pattern, checking in `onFlashLoan` that `sender` is the current contract is enough to trust that the contents of `data` are genuine.
### Flash lending security considerations
#### Automatic approvals for untrusted borrowers
Including in `onFlashLoan` the approval for the `lender` to take the `amount + fee` needs to be combined with a mechanism to verify that the borrower is trusted, such as those described above. An even safer approach is to implement the approval before the `flashLoan` is executed.
### Flash minting external security considerations
The typical quantum of tokens involved in flash mint transactions will give rise to new innovative attack vectors.
#### Example 1 - interest rate attack
If there exists a lending protocol that offers stable interests rates, but it does not have floor/ceiling rate limits and it does not rebalance the fixed rate based on flash-induced liquidity changes, then it could be susceptible to the following scenario:
FreeLoanAttack.sol
1. Flash mint 1 quintillion DAI
2. Deposit the 1 quintillion DAI + $1.5 million worth of ETH collateral
3. The quantum of your total deposit now pushes the stable interest rate down to 0.00001% stable interest rate
4. Borrow 1 million DAI on 0.00001% stable interest rate based on the 1.5M ETH collateral
5. Withdraw and burn the 1 quint DAI to close the original flash mint
6. You now have a 1 million DAI loan that is practically interest free for perpetuity ($0.10 / year in interest)
The key takeaway being the obvious need to implement a flat floor/ceiling rate limit and to rebalance the rate based on short term liquidity changes.
#### Example 2 - arithmetic overflow and underflow
If the flash mint provider does not place any limits on the amount of flash mintable tokens in a transaction, then anyone can flash mint 2^256-1 amount of tokens.
The protocols on the receiving end of the flash mints will need to ensure their contracts can handle this. One obvious way is to leverage OpenZeppelin's SafeMath libraries as a catch-all safety net, however consideration should be given to when it is or isn't used given the gas tradeoffs.
If you recall there was a series of incidents in 2018 where exchanges such as OKEx, Poloniex, HitBTC and Huobi had to shutdown deposits and withdrawls of ERC20 tokens due to integer overflows within the ERC20 token contracts.
### Flash minting internal security considerations
The coupling of flash minting with business specific features in the same platform can easily lead to unintended consequences.
#### Example - Treasury draining
In early implementations of the Yield Protocol flash loaned fyDai could be redeemed for Dai, which could be used to liquidate the Yield Protocol CDP vault in MakerDAO:
1. Flash mint a very large amount of fyDai.
2. Redeem for Dai as much fyDai as the Yield Protocol collateral would allow.
3. Trigger a stability rate increase with a call to `jug.drip` which would make the Yield Protocol uncollateralized.
4. Liquidate the Yield Protocol CDP vault in MakerDAO.
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).