Understanding Flash Loan Smart Contract
Developer guide to execute Unilend Flashloan
SETTING UP FLASHLOAN
UnilendFlashLoanOverview 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
pragma solidity 0.8.0;
// SPDX-License-Identifier: MIT
import "https://raw.githubusercontent.com/UniLend/flashloan_interface/main/contracts/UnilendFlashLoanReceiverBase.sol";
contract Flashloan is UnilendFlashLoanReceiverBase {
using SafeMath for uint256;
constructor() {}
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params
)
external
{
require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance, was the flashLoan successful?");
_params;
//
// Your logic goes here.
// !! Ensure that *this contract* has enough of `_reserve` funds to payback the `_fee` !!
//
uint totalDebt = _amount.add(_fee);
transferInternal(getUnilendCoreAddress(), _reserve, totalDebt);
}
function flashloanCall(address _asset, uint _amount) payable external {
bytes memory data;
flashLoan(address(this), _asset, _amount, data);
}
}
Last updated