Flash loans in Blockchain / Solidity - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
Flash loans are special blockchain transactions that borrow and repay funds instantly within one operation.
We want to understand how the time to execute a flash loan grows as the number of operations inside it increases.
Analyze the time complexity of the following flash loan code snippet.
function executeFlashLoan(address token, uint amount) external {
uint balanceBefore = IERC20(token).balanceOf(address(this));
lender.flashLoan(amount);
// Perform multiple operations with the loaned amount
for (uint i = 0; i < operations.length; i++) {
operations[i].execute();
}
require(IERC20(token).balanceOf(address(this)) >= balanceBefore, "Loan not repaid");
}
This code borrows tokens, runs several operations, then repays the loan in one transaction.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop running
operations[i].execute()repeatedly. - How many times: Once for each operation in the
operationslist.
Each added operation means one more execution step inside the loop.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 executions of operations |
| 100 | 100 executions of operations |
| 1000 | 1000 executions of operations |
Pattern observation: The total work grows directly with the number of operations.
Time Complexity: O(n)
This means the time to complete the flash loan grows in a straight line as you add more operations.
[X] Wrong: "The flash loan always takes constant time because it happens in one transaction."
[OK] Correct: Even though it is one transaction, the number of operations inside affects how long the transaction takes to run.
Understanding how the number of operations affects execution time helps you design efficient smart contracts and shows you can think about costs in blockchain programming.
"What if the operations inside the flash loan called other loops? How would the time complexity change?"
Practice
flash loan in blockchain?Solution
Step 1: Understand flash loan basics
Flash loans allow borrowing without collateral but require repayment in the same transaction.Step 2: Compare options
Only You can borrow funds without collateral but must repay within the same transaction correctly states no collateral and instant repayment.Final Answer:
You can borrow funds without collateral but must repay within the same transaction -> Option AQuick Check:
Flash loan = no collateral + instant repayment [OK]
- Thinking collateral is required
- Assuming repayment can be delayed
- Confusing flash loans with regular loans
Solution
Step 1: Identify the standard flash loan callback
The Aave protocol requires implementingexecuteOperationwith specific parameters.Step 2: Match function signature
function executeOperation(address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params) external returns (bool) matches the exact signature needed for flash loan execution and repayment.Final Answer:
function executeOperation(address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params) external returns (bool) -> Option DQuick Check:
executeOperation signature = function executeOperation(address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params) external returns (bool) [OK]
- Using incorrect function names
- Missing required parameters
- Wrong return type
executeOperation:
uint256 amountOwing = amounts[0] + premiums[0]; IERC20(assets[0]).approve(address(LENDING_POOL), amountOwing); return true;What does this code do?
Solution
Step 1: Understand the approval call
The code approves the lending pool contract to spend the loan amount plus premium from this contract.Step 2: Interpret the purpose
This approval is necessary so the lending pool can pull repayment automatically after the operation.Final Answer:
Approves the lending pool to withdraw the loan plus fee for repayment -> Option BQuick Check:
approve() = allow repayment withdrawal [OK]
- Confusing approve with transfer
- Thinking it sends funds to borrower
- Missing the premium fee in amount
executeOperation snippet:
function executeOperation(address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params) external returns (bool) {
uint256 amountOwing = amounts[0] + premiums[0];
IERC20(assets[0]).transferFrom(msg.sender, address(this), amountOwing);
return true;
}Solution
Step 1: Analyze repayment method
The code tries to pull repayment usingtransferFromfrommsg.sender, which is incorrect.Step 2: Correct repayment approach
Flash loans require approving the lending pool to pull funds, not transferring from msg.sender.Final Answer:
Using transferFrom instead of approve for repayment -> Option CQuick Check:
Repayment needs approve(), not transferFrom() [OK]
- Confusing transferFrom with approve
- Forgetting to approve lending pool
- Misunderstanding msg.sender role
executeOperation to profit and repay the loan?Solution
Step 1: Understand flash loan flow
You first borrow funds, then use them to buy low on one DEX and sell high on another to gain profit.Step 2: Approve repayment and finish
After trading, approve the lending pool to pull the loan plus fee, then return true to complete.Final Answer:
Borrow funds -> Buy low on DEX1 -> Sell high on DEX2 -> Approve repayment -> Return true -> Option AQuick Check:
Arbitrage flow = borrow -> trade -> approve -> return [OK]
- Approving repayment before trading
- Trying to trade before borrowing
- Not approving repayment at all
