Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article examines ERC3156, a standard proposing a mechanism for implementing flash loans on Ethereum.

The following material is translated, summarized, and supplemented with explanations.

I have also covered various other ERCs.

Overview

This ERC defines the rules and procedures for a particular type of transaction on Ethereum: the flash loan. A flash loan temporarily lends assets from one contract to another, with the assets required to be returned before the transaction ends. A small fee may also apply.

In this mechanism, the lending contract is called the lender contract, and the borrowing contract can use the assets for the duration of the transaction. The ERC defines an interface, meaning a common set of procedures for contract interactions, to facilitate safe and smooth lending and borrowing.

Imagine borrowing money from a bank briefly, doing something with that money, and returning the original amount plus a little extra before the transaction ends. This ERC is like a rulebook for safely performing the entire process of borrowing, using, and repaying assets on Ethereum.

Motivation

A flash loan is a smart contract mechanism for temporarily lending a specified quantity of tokens without collateral, with the entire operation taking place in one transaction. The borrowed tokens must be returned within that same transaction.

The early developers of flash loans devised a variety of interfaces and ways to use them. As a result, the technology needed to integrate different types of flash loans has become increasingly complex.

Differences among these protocols include the following.

Repayment Methods

The repayment method at the end of the transaction varies. Some contracts automatically withdraw the principal and fee, while others require the borrower to return both manually.

Repayment Currency

Some lenders allow loans to be repaid in a token different from the one originally borrowed. This can reduce the complexity and gas cost of flash transactions.

Consistency of Entry Points

Some lenders provide a single entry point regardless of whether the operation is a purchase, sale, deposit, or flash loan. Other protocols use separate entry points.

Flash Minting

Some lenders allow an arbitrary amount of their native token to be minted without fees, enabling flash loans limited by computational constraints rather than by asset holdings.

These features illustrate how flash loans have evolved and are used in various ways, with individual protocols offering distinct characteristics.

Flash loans use smart contracts to borrow assets temporarily under particular conditions. These systems vary, and their conditions and characteristics depend on the protocol used.

Specification

Flash lending integrates two smart contracts through a callback pattern. This EIP refers to them as the LENDER and RECEIVER.

LENDER

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


interface IERC3156FlashLender {

    /**
     * @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
    ) external view returns (uint256);

    /**
     * @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(
        address token,
        uint256 amount
    ) external view returns (uint256);

    /**
     * @dev Initiate a flash loan.
     * @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     */
    function flashLoan(
        IERC3156FlashBorrower receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external returns (bool);
}

The contract interface above defines the rules for providing flash loans on Ethereum. Called IERC3156FlashLender, it defines a set of functions and procedures that lenders must follow when providing flash loans.

The following explains the main functions included in this interface and how they work.

maxFlashLoan

Retrieves the maximum quantity of a token available to borrow. Returns 0 for unsupported tokens. It essentially asks, How much of this token can you lend?

flashFee

Calculates the fee charged for a loan. It reverts if the token is unsupported. It essentially asks, How much will this loan cost in fees?

flashLoan

javascript
function flashLoan(
    IERC3156FlashBorrower receiver,
    address token,
    uint256 amount,
    bytes calldata data
) external returns (bool) {
  ...
  require(
      receiver.onFlashLoan(msg.sender, token, amount, fee, data) == keccak256("ERC3156FlashBorrower.onFlashLoan"),
      "IERC3156: Callback failed"
  );
  ...
}

Executes a flash loan. The lender uses this function to temporarily lend a specified quantity of tokens to the borrower. The process must guarantee the following.

  • The original Japanese explanation places the onFlashLoan callback before the token transfer to the receiver. ERC3156 specifies the opposite order: transfer the tokens to the receiver before invoking the callback.
  • Pass the loan initiator (msg.sender) to onFlashLoan.
  • Pass the token, amount, and additional data to onFlashLoan unchanged.
  • Pass the loan fee to onFlashLoan so that the borrower can arrange repayment of the correct amount.
  • Verify that onFlashLoan returns the required hash value, confirming that the callback completed as expected.
  • Finally, recover the original loan amount plus the fee from the borrower.
    • If this fails, revert the transaction and invalidate the loan.

If everything succeeds, flashLoan returns true to indicate success. These steps are essential to ensuring that flash loans execute reliably and safely.

RECEIVER

javascript
pragma solidity ^0.7.0 || ^0.8.0;


interface IERC3156FlashBorrower {

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

A flash loan recipient must provide a contract implementing the IERC3156FlashBorrower interface. This interface defines the rules for receiving and processing flash loans.

onFlashLoan

This function is invoked automatically when a flash loan is received. It receives the loan initiator (initiator), token (token), borrowed amount (amount), fee (fee), and additional information (data).

The function must return a particular hash value (the keccak256 hash of ERC3156FlashBorrower.onFlashLoan) to acknowledge successful callback execution.

For the transaction to succeed, before onFlashLoan finishes, the receiver must make the principal (amount) plus the fee (fee) available for recovery by msg.sender, the lender. This enables the lender to collect repayment.

If onFlashLoan executes correctly and returns the required hash, the flash loan transaction can succeed, provided repayment also succeeds. This enables flash loans to be completed reliably and promptly.

Additional Details

This ERC provides a set of interfaces designed to support various flash lending scenarios while enabling safe and gas-efficient implementations.

  • flashFee reverts for unsupported tokens.
    • Returning a numeric value could be misleading.
  • The function name flashLoan is intuitive and unlikely to conflict with other contract functions.
    • It meets flash loan requirements regardless of whether the lender holds the tokens or mints them.
  • The receiver parameter allows the loan initiator and recipient to be different, providing implementation flexibility.
  • Existing flash lenders typically offer flash loans for multiple token types through one contract.
    • Including a token parameter in both flashLoan and onFlashLoan therefore closely matches existing functionality.
  • Including a bytes calldata data parameter allows the caller to pass arbitrary information to the receiver without compromising the usefulness of the flashLoan standard.
  • The function name onFlashLoan is also descriptive and unlikely to conflict with other functions in the receiver contract.
    • It follows the naming convention attributed to EIP667 in the original article.
  • The initiator (loan initiator) is normally needed in onFlashLoan, and the lender knows it as msg.sender.
    • Embedding initiator in the data parameter is possible, but is not recommended because the receiver would need an additional mechanism to verify its accuracy.
  • The amount is also needed in onFlashLoan, and the lender accepts it as a parameter.
    • Embedding amount in data would likewise require additional verification by the receiver.
  • The fee is usually calculated inside flashLoan, and the receiver needs to know it for repayment.
    • Passing the fee as a parameter is simpler and more effective than adding it to data.
  • The principal and fee are withdrawn from the receiver.
    • This enables the lender to implement other functions using transferFrom without locking them during the flash loan.
    • An alternative implementation could directly transfer repayment to the lender, but its other functions would then need to use transferFrom rather than transfer.
    • The simpler and more widely adopted pull architecture was chosen.

Backwards Compatibility

No backwards compatibility issues have been identified.

Implementation

Flash Borrower Reference Implementation

javascript
pragma solidity ^0.8.0;

import "./interfaces/IERC20.sol";
import "./interfaces/IERC3156FlashBorrower.sol";
import "./interfaces/IERC3156FlashLender.sol";


contract FlashBorrower is IERC3156FlashBorrower {
    enum Action {NORMAL, OTHER}

    IERC3156FlashLender lender;

    constructor (
        IERC3156FlashLender lender_
    ) {
        lender = lender_;
    }

    /// @dev ERC-3156 Flash loan callback
    function onFlashLoan(
        address initiator,
        address token,
        uint256 amount,
        uint256 fee,
        bytes calldata data
    ) external override returns(bytes32) {
        require(
            msg.sender == address(lender),
            "FlashBorrower: Untrusted lender"
        );
        require(
            initiator == address(this),
            "FlashBorrower: Untrusted loan initiator"
        );
        (Action action) = abi.decode(data, (Action));
        if (action == Action.NORMAL) {
            // do one thing
        } else if (action == Action.OTHER) {
            // do another
        }
        return keccak256("ERC3156FlashBorrower.onFlashLoan");
    }

    /// @dev Initiate a flash loan
    function flashBorrow(
        address token,
        uint256 amount
    ) public {
        bytes memory data = abi.encode(Action.NORMAL);
        uint256 _allowance = IERC20(token).allowance(address(this), address(lender));
        uint256 _fee = lender.flashFee(token, amount);
        uint256 _repayment = amount + _fee;
        IERC20(token).approve(address(lender), _allowance + _repayment);
        lender.flashLoan(this, token, amount, data);
    }
}

Action

javascript
enum Action {NORMAL, OTHER}

Overview

An enumeration for categorizing particular actions.

Details

This enumeration identifies different actions or states within the smart contract. For example, it can be used to switch between different function behaviors. It has two values, NORMAL and OTHER, used to adjust smart contract behavior appropriately.

Parameters

  • NORMAL
    • Represents ordinary behavior or state.
  • OTHER
    • Represents nonstandard or special behavior or state.

IERC3156FlashLender

javascript
IERC3156FlashLender lender;

Overview

A reference to an ERC3156-compliant lender contract providing flash loans.

Details

This variable holds a reference to a flash lender contract implementing the ERC3156 interface. It is used to request flash loans and call related functionality. When the smart contract uses a flash loan, it interacts with the lender contract through this variable.

Parameters

  • lender
    • A reference to an ERC3156-compliant lender contract.
    • Provides flash loan functionality.

onFlashLoan

javascript
function onFlashLoan(
    address initiator,
    address token,
    uint256 amount,
    uint256 fee,
    bytes calldata data
) external override returns(bytes32)

Overview

The callback function for an ERC3156 flash loan.

Details

The lender contract calls this function when a flash loan is requested. It performs verification and executes the operation corresponding to the specified action. For security, it verifies that the caller is a trusted lender and that the loan was initiated by this contract itself. After successful execution, it returns a specific hash to indicate normal completion.

Arguments

  • initiator
    • The flash loan initiator's address.
  • token
    • The address of the token used in the flash loan.
  • amount
    • The loan amount.
  • fee
    • The fee charged for the loan.
  • data
    • Arbitrary data.
    • In this example, it encodes an Action value indicating the operation type.

Return Value

  • bytes32
    • A specific hash value indicating successful completion.

flashBorrow

javascript
function flashBorrow(
    address token,
    uint256 amount
) public

Overview

Initiates a flash loan.

Details

This function requests a flash loan of the specified amount in the specified token. It calculates the fee, approves the tokens, and calls the lender contract's flashLoan function to initiate the loan. It is typically called when a user wants to use a flash loan.

Arguments

  • token
    • The address of the token used in the flash loan.
  • amount
    • The loan amount.

Return Value

  • The function has no return value, but internally calls flashLoan to initiate the flash loan process.

Flash Mint Reference Implementation

javascript
pragma solidity ^0.8.0;

import "../ERC20.sol";
import "../interfaces/IERC20.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 {

    bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan");
    uint256 public fee; //  1 == 0.01 %.

    /**
     * @param fee_ The percentage of the loan `amount` that needs to be repaid, in addition to `amount`.
     */
    constructor (
        string memory name,
        string memory symbol,
        uint256 fee_
    ) ERC20(name, symbol) {
        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
    ) external view override returns (uint256) {
        return type(uint256).max - totalSupply();
    }

    /**
     * @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) {
        require(
            token == address(this),
            "FlashMinter: Unsupported 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)` 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){
        require(
            token == address(this),
            "FlashMinter: Unsupported currency"
        );
        uint256 fee = _flashFee(token, amount);
        _mint(address(receiver), amount);
        require(
            receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS,
            "FlashMinter: Callback failed"
        );
        uint256 _allowance = allowance(address(receiver), address(this));
        require(
            _allowance >= (amount + fee),
            "FlashMinter: Repay not approved"
        );
        _approve(address(receiver), address(this), _allowance - (amount + fee));
        _burn(address(receiver), amount + fee);
        return true;
    }

    /**
     * @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(
        address token,
        uint256 amount
    ) internal view returns (uint256) {
        return amount * fee / 10000;
    }
}

CALLBACK_SUCCESS

javascript
bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan");

Overview

A constant indicating successful execution of the flash loan callback.

Details

This constant holds the keccak256 hash of the string ERC3156FlashBorrower.onFlashLoan, the expected return value when the flash loan callback completes successfully. The value is verified during the flash loan process to confirm that the callback executed correctly.


fee

javascript
uint256 public fee; //  1 == 0.01 %.

Overview

A variable representing the fee rate applied to flash loans.

Details

This variable stores the flash loan fee rate, typically expressed as a percentage. For example, 1 represents a fee rate of 0.01%. When a flash loan is executed, this rate is applied to the loan amount to calculate the fee payable by the borrower.


maxFlashLoan

javascript
function maxFlashLoan(
    address token
) external view override returns (uint256)

Overview

Retrieves the maximum quantity of a currency available to borrow.

Details

This function returns the maximum loan amount for the specified token. The maximum loan amount equals the maximum uint256 value minus the contract's total supply. It allows borrowers to determine available funds before requesting a flash loan.

Arguments

  • token
    • The address of the lending currency.

Return Value

  • uint256
    • The maximum amount of the specified token available to borrow.

flashFee

javascript
function flashFee(
    address token,
    uint256 amount
) external view override returns (uint256)

Overview

Retrieves the fee charged for a particular loan.

Details

It calculates and returns the loan fee for the specified token and amount. The fee is added to the principal at repayment. The fee is calculated by calling the internal _flashFee function. The function verifies whether the loan uses this contract's own currency.

Arguments

  • token
    • The address of the loan currency.
  • amount
    • The quantity of tokens being lent.

Return Value

  • uint256
    • The fee charged for the loan.

flashLoan

javascript
function flashLoan(
    IERC3156FlashBorrower receiver,
    address token,
    uint256 amount,
    bytes calldata data
) external override returns (bool)

Overview

Executes a flash loan.

Details

This function lends a specified quantity of tokens to receiver and collects the principal and fee after the ERC3156 callback. It verifies that the loan uses the contract's currency and confirms that the receiver processed the loan successfully. After verifying that the receiver has provided sufficient allowance, it burns the principal and fee.

Arguments

  • receiver
    • The contract receiving the tokens. It must implement IERC3156FlashBorrower.
  • token
    • The address of the loan currency.
  • amount
    • The quantity of tokens being lent.
  • data
    • Arbitrary data passed to receiver.

Return Value

  • bool
    • A Boolean indicating whether the loan succeeded.

_flashFee

javascript
function _flashFee(
    address token,
    uint256 amount
) internal view returns (uint256)

Overview

An internal function that calculates the fee for a specified loan.

Details

This function calculates the loan fee based on a particular token and amount. The fee is calculated as a proportion of the token amount and depends on the contract's fee variable. This internal utility is not directly accessible externally and is called by other functions.

Arguments

  • token
    • The address of the loan currency.
  • amount
    • The quantity of tokens being lent.

Return Value

  • uint256
    • The calculated fee.

Flash Loan Reference Implementation

javascript
pragma solidity ^0.8.0;

import "../interfaces/IERC20.sol";
import "../interfaces/IERC3156FlashBorrower.sol";
import "../interfaces/IERC3156FlashLender.sol";


/**
 * @author Alberto Cuesta Cañada
 * @dev Extension of {ERC20} that allows flash lending.
 */
contract FlashLender is IERC3156FlashLender {

    bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan");
    mapping(address => bool) public supportedTokens;
    uint256 public fee; //  1 == 0.01 %.


    /**
     * @param supportedTokens_ Token contracts supported for flash lending.
     * @param fee_ The percentage of the loan `amount` that needs to be repaid, in addition to `amount`.
     */
    constructor(
        address[] 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 `onFlashLoan(address user, uint256 amount, uint256 fee, bytes calldata)` 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,
        address token,
        uint256 amount,
        bytes calldata data
    ) external override returns(bool) {
        require(
            supportedTokens[token],
            "FlashLender: Unsupported currency"
        );
        uint256 fee = _flashFee(token, amount);
        require(
            IERC20(token).transfer(address(receiver), amount),
            "FlashLender: Transfer failed"
        );
        require(
            receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS,
            "FlashLender: Callback failed"
        );
        require(
            IERC20(token).transferFrom(address(receiver), address(this), amount + fee),
            "FlashLender: Repay failed"
        );
        return true;
    }

    /**
     * @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(
        address 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(
        address token,
        uint256 amount
    ) internal view returns (uint256) {
        return amount * fee / 10000;
    }

    /**
     * @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
    ) external view override returns (uint256) {
        return supportedTokens[token] ? IERC20(token).balanceOf(address(this)) : 0;
    }
}

CALLBACK_SUCCESS

javascript
bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan");

Overview

A constant indicating successful execution of the flash loan callback.

Details

This constant holds the keccak256 hash of the expected return value when the flash loan callback ERC3156FlashBorrower.onFlashLoan completes successfully. The value is checked against the callback's return value during the flash loan process to confirm that the expected result was returned.


supportedTokens

javascript
mapping(address => bool) public supportedTokens;

Overview

A mapping tracking supported tokens.

Details

This mapping tracks whether particular token addresses are supported by the contract. The token address is the key, and the value is a bool indicating whether the token is supported. The contract can therefore permit operations only for supported tokens and reject other tokens.

Parameters

  • address
    • The token address.
  • bool
    • A Boolean indicating whether the token is supported.

fee

javascript
uint256 public fee; //  1 == 0.01 %.

Overview

A variable representing the fee rate applied to flash loans.

Details

This variable stores the flash loan fee rate, typically expressed as a percentage. In this example, 1 represents a fee rate of 0.01%. When a flash loan is executed, the rate is applied to the loan amount to calculate the fee payable by the borrower.

Parameters

  • fee
    • A numeric value representing the flash loan fee rate.
    • 1 represents 0.01%.

flashLoan

javascript
function flashLoan(
    IERC3156FlashBorrower receiver,
    address token,
    uint256 amount,
    bytes calldata data
) external override returns(bool)

Overview

Temporarily lends a specified quantity of tokens and subsequently recovers the principal and fee.

Details

This function initiates the flash loan process and transfers tokens to the receiver. The receiver then executes the onFlashLoan callback and must arrange repayment of the loan and fee. The function verifies whether the token is supported for flash loans and returns whether the transaction succeeded.

Arguments

  • receiver
    • The contract receiving the tokens.
    • It must implement the IERC3156FlashBorrower interface.
  • token
    • The address of the loan currency.
  • amount
    • The quantity of tokens being lent.
  • data
    • Arbitrary data passed to the receiver.

Return Value

  • bool
    • A Boolean indicating whether the loan succeeded.

flashFee

javascript
function flashFee(
    address token,
    uint256 amount
) external view override returns (uint256)

Overview

Retrieves the fee charged for a particular loan.

Details

It calculates and returns the loan fee for the specified token and amount. The fee is calculated by calling the internal _flashFee function. The function verifies whether the loan uses a supported currency.

Arguments

  • token
    • The address of the loan currency.
  • amount
    • The quantity of tokens being lent.

Return Value

  • uint256
    • The fee charged for the loan.

_flashFee

javascript
function _flashFee(
    address token,
    uint256 amount
) internal view returns (uint256)

Overview

An internal function that calculates the fee for a specified loan.

Details

This function calculates the loan fee based on a particular token and amount. The fee is calculated as a proportion of the token amount and depends on the contract's fee variable. This internal utility is not directly accessible externally and is called by other functions.

Arguments

  • token
    • The address of the loan currency.
  • amount
    • The quantity of tokens being lent.

Return Value

  • uint256
    • The calculated fee.

maxFlashLoan

javascript
function maxFlashLoan(
    address token
) external view override returns (uint256)

Overview

Retrieves the maximum quantity of a currency available to borrow.

Details

This function returns the maximum loan amount for the specified token. For supported tokens, the maximum loan amount equals the contract's token balance. If the token is unsupported, it returns 0.

Arguments

  • token
    • The address of the lending currency.

Return Value

  • uint256
    • The maximum quantity of the specified token available to borrow.

Security

Verifying Callback Arguments

The onFlashLoan arguments describe the flash loan terms, but the information is not necessarily trustworthy. The following checks are necessary to verify the authenticity of these arguments.

Argument Verification

  • initiator (loan initiator), token (token), and amount (amount)
    • These refer to earlier transaction data, but may be unreliable because the caller of onFlashLoan could supply false information.
  • fee (fee)
    • It may be incorrect or miscalculated.
  • data (data)
    • It may be manipulated by the caller.

Establishing Trust

To establish that initiator, token, amount, and fee are correct, verify that the caller of onFlashLoan is on the trusted flash lender list. In many cases, the caller of flashLoan also receives the onFlashLoan callback, making this relatively straightforward. Otherwise, the flash lender must be approved in advance. To establish that data is correct, it is recommended to verify that initiator belongs to a trusted group of addresses in addition to performing the checks above.

These verification steps are important for safe and correct flash loan execution. Acting on unverified information may lead to incorrect results or malicious attacks. When using flash loans, understand these risks and implement appropriate verification.

Flash Lending Security

The following measures are important for securing flash lending.

Automated Approval

The safest approach is to approve the exact sum of the borrowed amount and fee before executing the flash loan. This helps prevent unauthorized transactions.

Verifying a Trusted Initiator

A receiver retaining allowances for the lender contract should verify within onFlashLoan that the loan initiator is trusted. This helps prevent unauthorized behavior by untrusted initiators.

Protecting Careless Contracts and EOAs

If a contract or EOA approves an ERC3156 lender contract and does not immediately use that allowance, and the lender fails to properly validate the onFlashLoan return value, a malicious third party could invoke flashLoan and drain funds from the contract or EOA up to the allowance or balance limit. To mitigate this risk, the lender must revert if onFlashLoan does not return the keccak256 hash of ERC3156FlashBorrower.onFlashLoan.

These measures are important to securing flash loans and reducing the risk of unauthorized use or loss of funds. Appropriate approval and verification mechanisms make flash loans safer to use.

External Security Considerations for Flash Minting

Flash minting enables very large quantities of tokens to be created temporarily within a transaction, potentially introducing new attack vectors.

Example: Interest Rate Attack

Consider a lending protocol offering stable interest rates. If the protocol has no minimum or maximum interest rate and the influx of funds through flash minting is not immediately reflected in interest rates, the following attack may be possible.

  1. Flash mint a large quantity of STAB tokens and deposit them together with ETH.
  2. The large deposit depresses the interest rate, making it possible to borrow STAB at almost no interest.
  3. The borrowed STAB can be used to close the original flash mint, leaving a large loan with almost no interest.

To avoid this scenario, impose minimum and maximum interest rates and adjust interest rates based on liquidity changes.

Example: Arithmetic Overflow and Underflow

If the flash mint provider places no limit on the amount of tokens that can be minted, anyone may mint an amount close to the maximum representable value. Transactions involving such large quantities of tokens may cause arithmetic overflow or underflow.

Protocols receiving flash-minted tokens must address these issues through a compiler with built-in overflow protection or explicit checks.

These examples illustrate that flash minting is useful, but its safe use requires careful design and adequate security measures. Appropriate limits and verification mechanisms can minimize attack risks.

Internal Security Considerations for Flash Minting

Flash minting can introduce unexpected problems when combined with particular business logic. For example, suppose a smart contract offers flash loans of its own token and borrows from a third party when that token is burned. Such a system may exhibit the following vulnerability.

  1. A large quantity of tokens (FOO) is flash minted and exchanged for another token (BAR).
    • This causes the lender contract to borrow from a third party (an underwriter) up to its borrowing limit.
  2. Increasing the debt ratio at the underwriter leaves the lender contract undercollateralized.
  3. The lender's assets can then be liquidated for profit because the lender is undercollateralized.

This example illustrates the importance of considering risks such as abrupt changes in liquidity and interest rates when implementing flash minting and introducing appropriate safeguards. These include monitoring token exchange rates, managing debt ratios, and implementing functionality to prevent unauthorized transactions. Appropriate safeguards allow the benefits of flash minting to be used while managing the associated risks.

Citation

Alberto Cuesta Cañada (@alcueca), Fiona Kobayashi (@fifikobayashi), fubuloubu (@fubuloubu), Austin Williams (@onewayfunction), "ERC-3156: Flash Loans," Ethereum Improvement Proposals, no. 3156, November 2020. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-3156.

Conclusion

This article covered ERC3156, a standard proposing a mechanism for implementing flash loans on Ethereum. I hope you found it useful.

If you have questions, feel free to contact me by direct message on Twitter.

Twitter @cardene777

I also share information on other platforms, so feel free to explore them.

https://chaldene.net/