🚧 This EIP had no activity for at least 6 months.

# EIP-3234: Batch Flash Loans Source

Author Alberto Cuesta Cañada, Fiona Kobayashi, fubuloubu, Austin Williams https://ethereum-magicians.org/t/erc-3234-batch-flash-loans/5271 Stagnant Standards Track ERC 2021-01-31

## Simple Summary

This ERC provides standard interfaces and processes for multiple-asset flash loans.

## Motivation

Flash loans of multiple assets, or batch flash loans, are a common offering of flash lenders, and have a strong use case in the simultaneous refinance of several positions between platforms. At the same time, batch flash loans are more complicated to use than single asset flash loans (ER3156). This divergence of use cases and user profiles calls for independent, but consistent, standards for single asset flash loans and batch flash loans.

## Specification

A batch 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 IERC3234BatchFlashLender interface.

pragma solidity ^0.7.0 || ^0.8.0;
import "./IERC3234BatchFlashBorrower.sol";

interface IERC3234BatchFlashLender {

/**
* @dev The amount of currency available to be lended.
* @param tokens The currency for each loan in the batch.
* @return The maximum amount that can be borrowed for each loan in the batch.
*/
function maxFlashLoan(
) external view returns (uint256[]);

/**
* @dev The fees to be charged for a given batch loan.
* @param tokens The loan currencies.
* @param amounts The amounts of tokens lent.
* @return The amount of each token to be charged for each loan, on top of the returned principal.
*/
function flashFee(
uint256[] calldata amounts
) external view returns (uint256[]);

/**
* @dev Initiate a batch flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param tokens The loan currencies.
* @param amounts The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function batchFlashLoan(
uint256[] calldata amounts,
bytes[] calldata data
) external returns (bool);
}


The maxFlashLoan function MUST return the maximum loan possible for each token. If a token is not currently supported maxFlashLoan MUST return 0, instead of reverting.

The flashFee function MUST return the fees charged for each loan of amount token. If a token is not supported flashFee MUST revert.

The batchFlashLoan function MUST include a callback to the onBatchFlashLoan function in a IERC3234BatchFlashBorrower contract.

function batchFlashLoan(
uint256[] calldata amounts,
bytes calldata data
) external returns (bool) {
...
require(
msg.sender,
tokens,
amounts,
fees,
data
) == keccak256("ERC3234BatchFlashBorrower.onBatchFlashLoan"),
"IERC3234: Callback failed"
);
...
}


The batchFlashLoan function MUST transfer amounts[i] of each tokens[i] to receiver before the callback to the borrower.

The batchFlashLoan function MUST include msg.sender as the initiator to onBatchFlashLoan.

The batchFlashLoan function MUST NOT modify the tokens, amounts and data parameters received, and MUST pass them on to onBatchFlashLoan.

The lender MUST verify that the onBatchFlashLoan callback returns the keccak256 hash of “ERC3234BatchFlashBorrower.onBatchFlashLoan”.

The batchFlashLoan function MUST include a fees argument to onBatchFlashLoan with the fee to pay for each individual token and amount lent, ensuring that fees[i] == flashFee(tokens[i], amounts[i]).

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.

If successful, batchFlashLoan MUST return true.

A receiver of flash loans MUST implement the IERC3234BatchFlashBorrower interface:

pragma solidity ^0.7.0 || ^0.8.0;

interface IERC3234BatchFlashBorrower {

/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param tokens The loan currency.
* @param amounts The amount of tokens lent.
* @param fees The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3234BatchFlashBorrower.onBatchFlashLoan"
*/
function onBatchFlashLoan(
uint256[] calldata amounts,
uint256[] calldata fees,
bytes calldata data
) external returns (bytes32);
}


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 onBatchFlashLoan.

If successful, onBatchFlashLoan MUST return the keccak256 hash of “ERC3156BatchFlashBorrower.onBatchFlashLoan”.

## 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 reverts on unsupported tokens, because returning a numerical value would be incorrect.

batchFlashLoan has been chosen as a function name 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 batchFlashLoan and onBatchFlashLoan 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 batchFlashLoan standard.

onBatchFlashLoan has been chosen as a function name as descriptive enough, unlikely to clash with other functions in the receiver, and following the onAction naming pattern used as well in EIP-667.

An initiator will often be required in the onBatchFlashLoan function, which the lender knows as msg.sender. An alternative implementation which would embed the initiator in the data parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable.

The amounts will be required in the onBatchFlashLoan function, which the lender took as a parameter. An alternative implementation which would embed the amounts in the data parameter by the caller would require an additional mechanism for the receiver to verify its accuracy, and is not advisable.

The fees will often be calculated in the batchFlashLoan function, which the receiver must be aware of for repayment. Passing the fees 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 features that depend on using transferFrom, without having to lock them for the duration of a flash loan. An alternative implementation where the repayment is transferred to the lender is also possible, but would need all other features in the lender to be also based in using transfer instead of transferFrom. Given the lower complexity and prevalence of a “pull” architecture over a “push” architecture, “pull” was chosen.

## Security Considerations

### Verification of callback arguments

The arguments of onBatchFlashLoan 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.

1. No arguments can be assumed to be genuine without some kind of verification. initiator, tokens and amounts refer to a past transaction that might not have happened if the caller of onBatchFlashLoan decides to lie. fees might be false or calculated incorrectly. data might have been manipulated by the caller.
2. To trust that the value of initiator, tokens, amounts and fees are genuine a reasonable pattern is to verify that the onBatchFlashLoan caller is in a whitelist of verified flash lenders. Since often the caller of batchFlashLoan will also be receiving the onBatchFlashLoan callback this will be trivial. In all other cases flash lenders will need to be approved if the arguments in onBatchFlashLoan are to be trusted.
3. To trust that the value of data is genuine, in addition to the check in point 1, it is recommended that the receiver verifies that the initiator is in some list of trusted addresses. Trusting the lender and the initiator is enough to trust that the contents of data are genuine.

### Flash lending security considerations

#### Automatic approvals for untrusted borrowers

The safest approach is to implement an approval for amount+fee before the batchFlashLoan is executed.

Including in onBatchFlashLoan 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.

If an unsuspecting contract with a non-reverting fallback function, or an EOA, would approve a lender implementing ERC3156, and not immediately use the approval, and if the lender would not verify the return value of onBatchFlashLoan, then the unsuspecting contract or EOA could be drained of funds up to their allowance or balance limit. This would be executed by a borrower calling batchFlashLoan on the victim. The flash loan would be executed and repaid, plus any fees, which would be accumulated by the lender. For this reason, it is important that the lender implements the specification in full and reverts if onBatchFlashLoan doesn’t return the keccak256 hash for “ERC3156FlashBorrower.onBatchFlashLoan”.

### 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 and related rights waived via CC0.
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 1, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.27787578105926514, "perplexity": 6707.194409362894}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2022-05/segments/1642320301341.12/warc/CC-MAIN-20220119125003-20220119155003-00110.warc.gz"}