Skip to main content

Free Flash Loans

Morpho’s (formerly known as Morpho Blue) singleton has a free flash loan function allowing one to borrow from all markets simultaneously, as long as they are repaid in the same transaction. This is typically useful in DeFi for liquidations, setting up leverage positions, and onchain arbitrages.

Overview

Flash loans are a unique concept in decentralized finance (DeFi) that allows users to borrow funds instantly without providing collateral. Aave is credited with creating the concept of flash loans. These loans are executed within a single blockchain transaction and must be repaid within the same transaction. They have been popularized by Aave and dYdX and are primarily designed for developers and users with technical knowledge.

If you are already familiar with the concept, jump into the implementation section or the technical reference of the flashLoan function.

Use case

Flash loans have various use cases, such as arbitrage, swapping collateral, and self-liquidation. However, they have also been associated with security implications, as they have been used in highly profitable DeFi exploits. Despite this, they are considered a groundbreaking innovation in the DeFi space.

Logic

Developers must write a smart contract that adheres to the following steps:

  1. Invoke the Morpho singleton contract using the flashLoan(address token, uint256 assets, bytes calldata data) function.
  2. The optionally provided data is then decoded in the onMorphoFlashLoan(uint256 assets, bytes calldata data) callback function.
  3. It must implement the onMorphoFlashLoan function which can execute arbitrary operations with the flash loaned assets. Note that:
    • If the requested quantity of assets is unavailable on the Morpho singleton contract, the transaction will revert.
    • The flash loaned assets must be available to be repaid by the end of the onMorphoFlashLoan call.
    • Morpho's contract must have a sufficient allowance to transfer the assets back to itself.

Implementation

FlashBorrowerMock.sol on Morpho's repository provides an example of a contract using a flash loan. Below is the implementation:

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;

import {IERC20} from "./interfaces/IERC20.sol";
import {IMorpho} from "../interfaces/IMorpho.sol";
import {IMorphoFlashLoanCallback} from "../interfaces/IMorphoCallbacks.sol";

contract FlashBorrowerMock is IMorphoFlashLoanCallback {
IMorpho private immutable MORPHO;

constructor(IMorpho newMorpho) {
MORPHO = newMorpho;
}

function flashLoan(address token, uint256 assets, bytes calldata data) external {
MORPHO.flashLoan(token, assets, data);
}

function onMorphoFlashLoan(uint256 assets, bytes calldata data) external {
require(msg.sender == address(MORPHO));
address token = abi.decode(data, (address));
IERC20(token).approve(address(MORPHO), assets);

// Add you logic here.
// e.g swap, liquidate, and much more...
}
}