Flash loan gas cost comparison

1 Overview

Flash loans can be used for various business operations like

  • arbitrage trades

  • self-hedging

  • self-liquidation

  • collateral swaps

  • debt refinancing (interest rate swap, currency swap)

  • other

All operations have an operational cost (transaction gas) that is made of two parts

  • borrowing and returning a flash loan

  • performing business operations

Business operations cost is dictated by the operational cost of actions on different decentralized exchanges or DeFi platforms. The operational cost of borrowing and returning a flash loan depends on the flash loan provider. In this document, we compare the operational costs of borrowing and returning flash loans via different platforms.

2 Operational cost of borrowing and returning a flash loan

We present the results of an objective comparison of flash loan costs in terms of gas. To date, we compared the following platforms

Platform

Transaction cost [Gas]

Gas cost compared to Equalizer

Gas profile

Transaction

Code

Equalizer

111752

100%

AAVE

204493

183%

dXdY

225223

200%

All tests are performed on Ethereum testnets.

Appendix

A.1 Equalizer flash loan receiver code

// Equalizer
/**
    Flash borrower example code
*/
contract FlashBorrowerExample is IERC3156FlashBorrower {
    uint256 MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;

    // @dev ERC-3156 Flash loan callback
    function onFlashLoan(
        address initiator,
        address token,
        uint256 amount,
        uint256 fee,
        bytes calldata data
    ) external override returns (bytes32) {       
        // Set the allowance to payback the flash loan
        IERC20(token).approve(msg.sender, MAX_INT);
        
        // This contract now has the funds requested.
        // Your logic goes here.
        
        // At the end of your logic above, this contract owes
        // the flashloaned amounts + premiums/fee.
        // Therefore ensure your contract has enough to repay
        // these amounts.
        
        // Return success to the lender, he will transfer get the funds back if allowance is set accordingly
        return keccak256('ERC3156FlashBorrower.onFlashLoan');
    }
}

A.2 AAVE flash loan receiver code

// AAVE
/**
    Flash borrower example code
*/
contract Flashloan is FlashLoanReceiverBase {

    constructor(address _addressProvider) FlashLoanReceiverBase(_addressProvider) public {}

    /**
        This function is called after your contract has received the flash loaned amount
     */
    function executeOperation(
        address _reserve,
        uint256 _amount,
        uint256 _fee,
        bytes calldata _params
    )
    external
    override
    {
        require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance, was the flashLoan successful?");

        // This contract now has the funds requested.
        // Your logic goes here.
        
        // At the end of your logic above, this contract owes
        // the flashloaned amounts + premiums/fee.
        // Therefore ensure your contract has enough to repay
        // these amounts.

        uint totalDebt = _amount.add(_fee);
        transferFundsBackToPoolInternal(_reserve, totalDebt);
    }

    /**
        Flash loan 1000000000000000000 wei (1 ether) worth of _asset
     */
    function flashloan(address _asset) public onlyOwner {
        bytes memory data = "";
        uint amount = 1 ether;

        ILendingPool lendingPool = ILendingPool(addressesProvider.getLendingPool());
        lendingPool.flashLoan(address(this), _asset, amount, data);
    }
}

A.3 dXdY flash loan receiver

// dXdY
/**
    Flash borrower example code
*/
function flashLoan(uint loanAmount) external {
    /*
    The flash loan functionality in dydx is predicated by their "operate" function,
    which takes a list of operations to execute, and defers validating the state of
    things until it's done executing them.
    
    We thus create three operations, a Withdraw (which loans us the funds), a Call
    (which invokes the callFunction method on this contract), and a Deposit (which
    repays the loan, plus the 2 wei fee), and pass them all to "operate".
    
    Note that the Deposit operation will invoke the transferFrom to pay the loan 
    (or whatever amount it was initialised with) back to itself, there is no need
    to pay it back explicitly.
    
    The loan must be given as an ERC-20 token, so WETH is used instead of ETH. Other
    currencies (DAI, USDC) are also available, their index can be looked up by
    calling getMarketTokenAddress on the solo margin contract, and set as the 
    primaryMarketId in the Withdraw and Deposit definitions.
    */

    Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);

    operations[0] = Actions.ActionArgs({
    actionType: Actions.ActionType.Withdraw,
    accountId: 0,
    amount: Types.AssetAmount({
    sign: false,
    denomination: Types.AssetDenomination.Wei,
    ref: Types.AssetReference.Delta,
    value: loanAmount // Amount to borrow
    }),
    primaryMarketId: 0, // WETH
    secondaryMarketId: 0,
    otherAddress: address(this),
    otherAccountId: 0,
    data: ""
    });

    operations[1] = Actions.ActionArgs({
    actionType: Actions.ActionType.Call,
    accountId: 0,
    amount: Types.AssetAmount({
    sign: false,
    denomination: Types.AssetDenomination.Wei,
    ref: Types.AssetReference.Delta,
    value: 0
    }),
    primaryMarketId: 0,
    secondaryMarketId: 0,
    otherAddress: address(this),
    otherAccountId: 0,
    data: abi.encode(
        // Replace or add any additional variables that you want
        // to be available to the receiver function
            msg.sender,
            loanAmount
        )
    });

    operations[2] = Actions.ActionArgs({
    actionType: Actions.ActionType.Deposit,
    accountId: 0,
    amount: Types.AssetAmount({
    sign: true,
    denomination: Types.AssetDenomination.Wei,
    ref: Types.AssetReference.Delta,
    value: loanAmount + 2 // Repayment amount with 2 wei fee
    }),
    primaryMarketId: 0, // WETH
    secondaryMarketId: 0,
    otherAddress: address(this),
    otherAccountId: 0,
    data: ""
    });

    Account.Info[] memory accountInfos = new Account.Info[](1);
    accountInfos[0] = Account.Info({owner: address(this), number: 1});

    soloMargin.operate(accountInfos, operations);
}

// This is the function called by dydx after giving us the loan
function callFunction(address sender, Account.Info memory accountInfo, bytes memory data) external override {
    // Decode the passed variables from the data object
    (
    // This must match the variables defined in the Call object above
    address payable actualSender,
    uint loanAmount
    ) = abi.decode(data, (
        address, uint
        ));

    // We now have a WETH balance of loanAmount. The logic for what we
    // want to do with it goes here. The code below is just there in case
    // it's useful.

    // It can be useful for debugging to have a verbose error message when
    // the loan can't be paid, since dydx doesn't provide one
    require(WETH.balanceOf(address(this)) > loanAmount + 2, "CANNOT REPAY LOAN");
    // Leave just enough WETH to pay back the loan, and convert the rest to ETH
    //  WETH.withdraw(WETH.balanceOf(address(this)) - loanAmount - 2);
    // Send any profit in ETH to the account that invoked this transaction
    //  actualSender.transfer(address(this).balance);
}

Last updated