UniLend
Search…
Understanding Flash Loan Smart Contract
Developer guide to execute Unilend Flashloan
SETTING UP FLASHLOAN
Please note that executing a flash loan is a complex transaction and the user should have a sound understanding of Solidity to fully comprehend the structure and models used within the smart contracts.
Overview of cycle to execute flash loan:
  • Your contract _receiver calls the Unilend smart contract, requesting loan of certain _amount from the _reserve.
  • Unilend smart contract runs some sanity check and then transfer the _amount
    from the _reserve to your contract _receiver.
  • Your contract _receiver holding the _amount execute implementation of your code.
  • Once your code is executed you transfer the flash loan _amount to _reserve along with _fee.
Parameters
Type
Defination of parameters
_receiver
address
address of the contract receiving the funds.
_reserve
address
addresses of the reserves to flash loan
_amount
uint256
amounts of _asset to flashloan.
_fee
uint256
premium incured over the loan _amount
_params
bytes
bytes-encoded parameters to be used by the _receiver contract

1. Create your flash loan contract

To develop your own flash loan contract, start building contract interface over Unilend library UnilendFlashLoanReceiverBase
2. Executing flash loan
Create a executeOperation() function within the contract for implementing your arbitary logic and requesting fund with local function transferInternal()
3. Calling flash loan
Define a flashloanCall() function inside your smart contract taking relevant parameters as _asset and _amount that would be passed to local function flashLoan() of UnilendFlashLoanRecieverBase
4. Completing flash loan transaction
Once you have performed your logic with the flash loaned assets (in your executeOperation() function), you will need to pay back the flash loaned amounts. In the payback cycle ensure that *your contract* has enough of funds to pay the _fee
1
pragma solidity 0.8.0;
2
// SPDX-License-Identifier: MIT
3
4
import "https://raw.githubusercontent.com/UniLend/flashloan_interface/main/contracts/UnilendFlashLoanReceiverBase.sol";
5
6
7
contract Flashloan is UnilendFlashLoanReceiverBase {
8
using SafeMath for uint256;
9
10
constructor() {}
11
12
function executeOperation(
13
address _reserve,
14
uint256 _amount,
15
uint256 _fee,
16
bytes calldata _params
17
)
18
external
19
{
20
require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance, was the flashLoan successful?");
21
_params;
22
23
//
24
// Your logic goes here.
25
// !! Ensure that *this contract* has enough of `_reserve` funds to payback the `_fee` !!
26
//
27
28
29
uint totalDebt = _amount.add(_fee);
30
transferInternal(getUnilendCoreAddress(), _reserve, totalDebt);
31
}
32
33
function flashloanCall(address _asset, uint _amount) payable external {
34
bytes memory data;
35
36
flashLoan(address(this), _asset, _amount, data);
37
}
38
}
Copied!
Last modified 7mo ago
Copy link
Contents