Alberto Cuesta Cañada
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
1
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- eip: <to be assigned> title: Flash Loans author: Alberto Cuesta Cañada (@albertocuestacanada), Fiona Kobayashi (@fifikobayashi), fubuloubu (@fubuloubu) discussions-to: https://ethereum-magicians.org/t/flash-loan-eip-early-draft/4993/2 status: Draft type: Standards Track category: ERC created: 2020-11-15 --- <!--This is the suggested template for new EIPs. Note that an EIP number will be assigned by an editor. When opening a pull request to submit your EIP, please use an abbreviated title in the filename, `eip-draft_title_abbrev.md`. The title should be 44 characters or less.--> ## Simple Summary Flash loaning allows 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. The aim of this ERC is to provide a standard interfaces and processes for flash lenders and borrowers, allowing for flash loan integration without a need to consider each particular implementation. ## Abstract Flash loans are rapidly gaining popularity. A standard that guides the community to use the same interface will allow for greater interoperability in the future. The use of standard processes and a clear description of the risks associated with flash loans will allow the community to create safer smart contracts. ## Motivation 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. A `receiver` of flash mints MUST implement an `onFlashLoan` callback: ``` interface FlashBorrowerLike { function onFlashLoan(address sender, uint256 amount, uint256 fee, bytes calldata) external; } ``` On the callback execution the `receiver` MUST have received `amount` tokens from the caller. The `receiver` can trust that `sender` is the account that initiated the flash loan in the caller. For the transaction to not revert, `receiver` MUST send `amount + fee` to the caller. Before that, the `receiver` can implement any logic it desires. The token contract implementing a flash lending feature MUST implement a `flashLoan` function: ``` function flashLoan(address receiver, uint256 amount, bytes calldata data) external { ... FlashBorrowerLike(receiver).onFlashLoan(msg.sender, amount, fee, data); ... } ``` The `flashLoan` function MUST execute the equivalent of an `ERC20.transfer` operation before calling `FlashBorrowerLike(receiver).onFlashLoan(...)`. The lender contract MAY `mint` the tokens lended, instead of executing a `transfer` of tokens it holds. The `flashLoan` function MUST verify that the tokens lended were returned, and MUST NOT take them from the `receiver`. The `receiver` MUST take an action to return `amount + fee` tokens and allow the transaction to resolve. If the `flashLoan` used tokens generated by a `mint`, they SHOULD be the target of a `burn` before the end of the transaction. If a fee is charged, the contract implementing `flashLoan` MAY use it in any desired way (e.g. the fee can be burned or transferred to any other party). ## 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. `flashLoan(address receiver, 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 `flashLoan` to be called by EOAs, as opposed to the pattern in which `onFlashLoan` is called on `msg.sender`. This allows the lender to inform the `receiver` which address called `flashLoan`. This particular setup allows the `receiver` to implement an account based platform. A `bytes calldata data` parameter is included for the caller to pass arbitrary information to the `receiver`, without impacting the utility of the `flashMint` 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 `user` will often be required in the `onFlashLoan` function, which the lender knows as `msg.sender`. An alternative implementation which would embed the `user` 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 `flashMint` 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. ## Backwards Compatibility No backwards compatibility issues identified. ## Test Cases [WETH10](https://github.com/WETH10/WETH10/pull/81), [MakerDAO](https://github.com/hexonaut/dss-flash/pull/18). ## Implementation [WETH10](https://github.com/WETH10/WETH10/pull/81), [MakerDAO](https://github.com/hexonaut/dss-flash/pull/18). ## Security Considerations ### Flash lending security considerations #### Example - Transfer from receiver An implementation that allows flash lending to an arbitrary target, and that also takes the flash loaned amount from such target at the end of the transaction can be used to drain assets of a smart contract that trades a pair of assets based on internal balances. 1. The attacker triggers a flash loan of 1 million DAI to an AMM trading DAI/ETH. 2. The attacker sells 1000 ETH to the AMM trading pair, obtaining a larger amount of DAI than the pre-transaction price would have returned. 3. The flash lender burns the 1 million DAI (plus possibly a fee) from the receiver (AMM trading pair), which bears the loss of having sold DAI to the attacker at an artificially depressed price. The key takeaway being that smart contracts trading on balances should not give blanket transfer approvals to smart contracts with flash loan features, unless they can be certain of their implementation. ### 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/).

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully