Table of contents (9 sections)
I was reading Building Full Stack DeFi Applications (Samuel Zhou, Packt, 2024). The book builds a decentralized finance application, or DeFi. These are programs, the contracts, that swap and lend tokens (digital currencies) with no bank.
These programs live on a blockchain such as Ethereum, a public ledger kept up to date by a network of computers, with no owner. You send it transactions, orders grouped into batches, the blocks, validated about every 12 seconds.
I write Go in crypto fintech, with PostgreSQL behind it. One detail in the book made me think of a database. Its lending pool, a shared reserve where you deposit and borrow tokens, does not credit interest account by account. It changes a single number, and every lender gets richer at once: one UPDATE on one row. Hence the question: can you write a DeFi in pure SQL? I tried, and the result is called the POC here: public code, on GitHub, that replays everything in SQL. It holds this lending pool and the token swap of Uniswap v2, one of the best-known exchange contracts. The book describes a price manipulation attack against the lending pool, and the POC replays it. The whole thing fits in seven SQL files and 319 automated checks.
The math of the swap, the loan and the attack replays. The seven test cases published by Uniswap give the same amount down to the last decimal. A backend dev gets a landmark out of it: where the usual tools (UPDATE, view, trigger, transaction) are enough, and where they stop. What does not replay comes down to one question: whom do you have to believe? That question separates a blockchain from a database.
$ git clone https://github.com/ohugonnot/defi-en-sql $ cd defi-en-sql && make test
The POC: a mini Uniswap v2 and a lending pool in PostgreSQL 18, launched by Docker. Each line below says what is proven, and by which test.
- VerifiedThe seven Uniswap v2 test cases give the same amount, down to the last decimal:
tests/t01_amm.sql. - VerifiedThe same attack drains the lending pool that reads the spot price. It fails against an average price:
tests/t05_oracle_attaque.sql. - VerifiedThe tests fail if the code is deliberately broken in 76 ways:
make mutation. That is mutation testing: you break the code on purpose to see whether the tests catch it. - Not verifiedNothing here simulates a network, or an adversary who chooses the order of transactions. The last part explains why that gap is the whole point.
- Not verifiedThe attack amounts depend on the pool sizes chosen for the test. They cannot be compared with those of the book.
A token swap is an UPDATE, provided you pick the right type
A swap pool is a shared pot that holds two tokens, say 5 tokens A and 10 tokens B. Its rule: a swap never lowers the product of the two quantities, called K. Here, K is 5 × 10 = 50. You bring 1 A, and the pool goes to 6 A. To keep the product at 50, it can keep only 50 / 6 = 8.33 B. So it gives you back 10 − 8.33 = 1.67 B. The reading note on the book shows why the price rises with every purchase.
The pool counts what it holds twice:
- Its reserves are the two numbers it wrote on its table row.
- Its actual balance is what it really owns.
Between two operations, the two are equal. During a swap, they diverge: the tokens arrive in the pool's account before the row is updated. The K check then verifies that the product of the balances after the operation is at least the product of the reserves written before.
The pool also takes 0.3% in fees: only 997 thousandths of your input count in the calculation. You then receive 1.662497915624478906 B. That number is not mine: it is the first case of the public Uniswap tests, and the SQL must find it down to the last decimal. Those 18 decimals are the ones tokens use, explained right below.
First trap, the type. An Ethereum contract knows no floating-point numbers: it counts in integers. A token often has 18 decimals, so 1 token is written 10^18 units. For ETH, the currency of Ethereum, this smallest unit is called the wei. The POC reuses that name for all its tokens. PostgreSQL's bigint, the usual integer, stops around 9.2 × 10^18 and overflows as soon as you multiply two amounts.
The largest integer type of a contract, uint256, goes up to 78 digits. So I took NUMERIC(78,0): a decimal number of at most 78 digits, with 0 after the decimal point. A CHECK, a rule that PostgreSQL verifies on every write, caps it at 2^256 − 1.
Second trap, sneakier: division. Solidity, the language of contracts, divides two integers and drops the remainder. PostgreSQL's /, on a NUMERIC, rounds to the nearest, at a precision it picks on its own. For 2e18::numeric / 3, it keeps no decimals and returns 666666666666666667. The rounding has already happened, so a trunc placed afterwards fixes nothing. The div() function truncates like Solidity: it returns 666666666666666666.
One wei of difference looks ridiculous. Yet Uniswap and the book always round in favor of the pool: the other way, every repeated operation would take a wei from it.
So the POC divides with div_bas and div_haut, two small functions built on div(). They round down or up as needed. The first token deposit into a pool needs a square root, that of A × B (the Uniswap rule). But sqrt() rounds too, so the POC replaces it with an exact integer root.
Here is the calculation of the amount returned, the one in Uniswap's getAmountOut. It is "K does not go down" written as one division. Without fees, the output is entree × reserve_sortie / (reserve_entree + entree), so 1 × 10 / (5 + 1) ≈ 1.67 B. With fees, the input is multiplied by 997 / 1000: frais_pour_mille is 3, so 1000 - frais_pour_mille is the 997:
-- getAmountOut of Uniswap v2, rounded down so the pool never pays a wei too much.
CREATE FUNCTION montant_sortie(entree numeric, reserve_entree numeric, reserve_sortie numeric,
frais_pour_mille int DEFAULT 3) RETURNS numeric
LANGUAGE sql IMMUTABLE AS $$
SELECT div_bas(entree * (1000 - frais_pour_mille) * reserve_sortie,
reserve_entree * 1000 + entree * (1000 - frais_pour_mille))
$$;
Full file: sql/01_amm.sql, lines 42 to 48
The book takes 0.2% in fees, Uniswap 0.3%. The POC keeps 0.3% by default to match the Uniswap tests, and switches to 0.2% to replay the book. Over more than 9,000 random swaps, K never went down. The fees stay in the pool, so K even rises a little.
A lending pool: one UPDATE for interest, one SELECT for liquidations
The book's lending pool looks like a shared piggy bank. You deposit 100 WETH (ETH in token form), and you get 100 shares: one share is worth 1 WETH at the start. Borrowers pay interest into the piggy bank, and the number of shares does not move. So each share is worth more.
In the database, the tables follow this picture. The pret_pool table holds one row per pool, with the total deposited and the number of shares. The pret_position table holds one row per lender, with their shares. When interest lands, only the pret_pool row changes. The value of a share, the total divided by the number of shares, is computed on read.
In the test, we take rounder numbers: 1,000 WETH are deposited against 1,000 shares. Then 800 are borrowed for a year at 9% (rate explained below). The interest is 800 × 9% = 72 WETH. A share is worth (1,000 + 72) / 1,000 = 1.072, and 100 shares withdraw for 107.2 WETH. One UPDATE (the SQL statement that changes a row), whatever the number of lenders.
On chain, this trick is not a matter of style. Every operation of a contract burns gas, a unit of computation that the caller pays in ETH. Looping over a thousand accounts would cost a thousand times more. The pool keeps the cost constant.
The borrow rate depends on utilization, the share of the pool already lent out. The book makes it rise in two slopes. It goes gently from 1% to 9% up to a threshold, the kink, then climbs to 60% when everything is lent. The POC puts the kink at 80% utilization. The book reads that value from Aave v2's ETH pool, a large lending protocol. Aave's original code set 65%, a setting the protocol can change. The POC keeps 80% everywhere.
-- Borrow rate at a given utilisation: a gentle line up to the kink, a steep one after it.
CREATE FUNCTION taux_emprunt(utilisation numeric, p pret_pool) RETURNS numeric
LANGUAGE sql IMMUTABLE AS $$
SELECT p.taux_base + CASE WHEN utilisation <= p.utilisation_optimale
THEN div_bas(p.ecart_optimal * utilisation, p.utilisation_optimale)
ELSE p.ecart_optimal + div_bas(p.ecart_exces * (utilisation - p.utilisation_optimale),
1e18 - p.utilisation_optimale)
END
$$;
Full file: sql/03_pret.sql, lines 35 to 43
The columns of pret_pool carry these settings, and p pret_pool is the row of the pool in question:
taux_base: the rate at zero utilization, 1%.ecart_optimal: the rise up to the kink, 8 percentage points. At 80%, 1 + 8 = 9%.ecart_exces: the rise from the kink to 100%, 51 points. At 100%, 9 + 51 = 60%.utilisation_optimale: the kink, 80%.
Rates are integers scaled by 10^18, as in a contract. A contract cannot write a decimal point: everything is multiplied by a billion billion, and 1e18 is 100%. At 80% utilization, the function returns 9% for the borrower. On the 800 WETH borrowed, that is 72 WETH of interest, as in the test above. Set against the 1,000 WETH deposited, it gives 7.2% for the lender: only 80% of the pool earns anything. The book's reading note details the curve.
Finding the accounts to liquidate is a SELECT, and a contract cannot afford it
To borrow, you deposit collateral. The pool lends you only a fraction of its value: 80% in the POC, as in the book's attack. With 100 WETH of collateral, your borrowing cap is therefore 80 WETH. This 80% has nothing to do with the rate kink, which is also 80% by chance. The collateral can be a different token from the one you borrow: its price is then what moves the cap.
If the collateral price drops, the debt can exceed the cap. The account becomes unhealthy, and anyone can liquidate it: repay part of its debt in its place. In exchange, the liquidator receives collateral worth the amount repaid, plus a 10% bonus in the book's example.
So the same 80% plays two roles in the book and in the POC. It is the borrowing cap, and the liquidation threshold: the debt beyond which the account becomes unhealthy. Aave separates the two: for ETH, 80% as the cap and 82.5% as the threshold, in its original configuration. The list of unhealthy accounts is a view, that is, a saved query you read like a table:
CREATE VIEW v_compte AS
SELECT v.compte,
SUM(CASE WHEN v.depot > 0
THEN div_bas(div_bas(v.depot * prix_garantie(v.jeton), 1e18) * v.taux_garantie, 1e18) ELSE 0 END) AS max_empruntable,
SUM(CASE WHEN v.dette > 0
THEN div_haut(v.dette * prix(v.jeton), 1e18) ELSE 0 END) AS dette
FROM v_position v
WHERE v.depot > 0 OR v.dette > 0
GROUP BY v.compte;
CREATE VIEW v_compte_malsain AS
SELECT * FROM v_compte WHERE dette > max_empruntable;
Full file: sql/05_liquidation.sql, lines 13 to 24
v_position is another view of the POC. It gives one row per account and per token, with the amount deposited and the debt. Each row reads the price of its token through prix(), the oracle of the POC, which has its own section below. The collateral goes through prix_garantie(), which is 0 as long as the token has no price yet. Without it, a debtor could deposit 1 wei of a token with no price, and the whole view would fail with an error, liquidation included. The debt keeps a strict price. max_empruntable is the cap of the account, with SUM … GROUP BY adding up its rows. The cap is rounded down and the debt rounded up: the account looks less healthy than it is, never more.
So far, SQL was imitating the chain. Here, it is the chain that would need SQL. A contract cannot run this SELECT: looping over all its accounts would cost too much gas, and it acts only when someone calls it. The book admits this in its last lesson and proposes a script that watches the accounts. So this query must run off chain. The SELECT does exist, but at the liquidator, whom the bonus pays to run it.
Send first, check at COMMIT: the flash swap as a deferred constraint
The word transaction comes from databases too. A transaction groups several writes that all go through at COMMIT, or all vanish at ROLLBACK. Ethereum follows the same rule: a transaction that fails has all its writes undone.
Uniswap v2 uses this for a surprising mechanism, the flash swap. The pool sends you the tokens before you have paid. You use them, then you repay, in the same transaction. At the end of its swap call, the Uniswap function that runs an exchange, the contract checks K. If it went down, all writes are undone. Nobody needs to trust you: you could never walk away with the tokens.
The POC does it a little differently, on purpose: it checks K at COMMIT, at the end of the whole transaction. That is wider than Uniswap: you can chain other calls before repaying, outside the borrowed pool, as the attack below does.
PostgreSQL has the same shape, the deferred constraint, and it is the sharpest likeness in the whole POC. A trigger is a function the database runs by itself when you write to a table. An ordinary trigger fires with the statement that writes. A constraint trigger (CREATE CONSTRAINT TRIGGER) declared DEFERRABLE INITIALLY DEFERRED waits for the COMMIT. If it raises an error, the COMMIT fails and everything is rolled back. Here, it sits on the flash_swap table, one row per loan:
CREATE CONSTRAINT TRIGGER flash_swap_rembourse
AFTER INSERT ON flash_swap
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION verifier_flash_swap();
Full file: sql/02_flash_swap.sql, lines 34 to 37
The flash_swap() function sends the tokens and records the loan in this table. At COMMIT, the trigger reruns the K check. The product of the actual balances, fees deducted, must stay at least equal to that of the recorded reserves. This is Uniswap's require(…, 'UniswapV2: K'). In the test that does not repay, the COMMIT fails and the tables return to their earlier state.
The likeness has two limits, and an expert will point them out:
- Between the send and the check, Uniswap runs the borrower's code, a stranger's. In the POC, the database runs only functions written by its operator. That does not protect against reentrancy: during the loan, the borrower calls the public functions of the same pool again, before the check. So the POC locks the pool with a flag, like Uniswap's
lockmodifier: any call receivesUniswapV2: LOCKEDuntil K is checked. - A PostgreSQL superuser, the account with all rights, can disable the trigger. Keep this point in mind, it comes back at the end.
The oracle attack fits in a single transaction
The lending pool must know the price of your collateral. It asks an oracle, a contract that gives a price. The book's first oracle reads this price in a swap pool. It is the ratio of the two reserves, WETH divided by tokens, that is, the price of the token. But a big purchase moves this ratio, within the buyer's own transaction. The book draws an attack from it, which I already told here. This time, I ran it.
The setup is three pools: two swap pools and the lending pool. Each swap pool takes 0.2% in fees, as in the book: only 998 thousandths of the input count in the calculation. Pool 2 holds 10 BAR (a test token) and 1 WETH: one BAR is worth 0.1 WETH. The lending pool holds 100 WETH. Pool 1, a large FOO/WETH pool (FOO, another test token), only serves to lend its 99 WETH to the attacker by flash swap. The attacker starts with zero, and the whole attack fits in one function:
CREATE FUNCTION attaque() RETURNS void LANGUAGE plpgsql AS $$
DECLARE bar numeric;
BEGIN
PERFORM flash_swap(1, 0, 99e18);
bar := echanger(2, 'WETH', 99e18);
PERFORM deposer('BAR', 0.2e18);
PERFORM emprunter('WETH', 100e18);
PERFORM echanger(2, 'BAR', bar - 0.2e18);
PERFORM transferer(caisse(1), 'WETH', div_haut(99e18 * 1000, 998));
END $$;
Full file: tests/t05_oracle_attaque.sql, lines 20 to 29
Line by line, knowing that bar holds the number of BAR received at step 2:
- The attacker borrows 99 WETH from pool 1, by flash swap:
flash_swap(1, 0, 99e18)asks for zero FOO and 99 WETH. - He buys BAR from pool 2 with these 99 WETH, and the price of BAR skyrockets.
- He deposits 0.2 BAR as collateral, which the oracle values at the inflated price.
- He borrows the 100 WETH of the lending pool.
- He sells back to pool 2 the BAR he did not deposit.
- He repays the flash swap into pool 1: 99 × 1000 / 998 = 99.20 WETH. The 0.2% fee lets only 998 thousandths count.
After the purchase, pool 2 holds 100 WETH (1 + 99). Without fees, it would keep 0.1 BAR and BAR would be worth 100 / 0.1 = 1,000 WETH. With fees, only 998 thousandths of the 99 WETH count for its output: it keeps a bit more, about 0.1002 BAR. So BAR is worth 100 / 0.1002, that is 998 WETH instead of 0.1. The 0.2 BAR deposited pass for collateral worth nearly 200 WETH (0.2 × 998). At 80%, the borrowing cap reaches about 160 WETH, more than the 100 WETH of the lending pool.
The final count is easy to follow in order. The attacker borrows 100 WETH from the lending pool, then sells his BAR back for 98.98 WETH. He returns 99.20 WETH to the flash swap, the 99 borrowed plus the fees. He is left with 100 + 98.98 − 99.20 = 99.78 WETH. That is almost the 99 spent on the purchase, since pool 2 buys back what it just sold. His debt stays backed by 0.2 BAR worth 0.02 WETH: the lenders lost their money.
The book's defense is an average price, the Uniswap v2 oracle. The pool keeps a counter. At the first operation of each block, it adds the last known price to it, multiplied by the seconds elapsed. A price weighs as much as it lasted. The oracle reads this counter twice, 720 seconds apart: that is its window, 60 blocks of 12 seconds. The gap between the two readings, divided by 720, gives the average price. I reran the same function with this oracle, then a second, slower scenario:
| Oracle | BAR price read | Result |
|---|---|---|
| Spot price | 998 WETH | Attack succeeds, 99.78 WETH gained |
| Average price, attack in one transaction | 0.1 WETH | Borrow refused: ACCOUNT_UNHEALTHY, the account is unhealthy |
| Average price, read at the next block | 16.73 WETH | Price inflated 167 times, but the borrowing cap of 0.2 BAR is only about 2.7 WETH (0.2 × 16.73 × 80%) |
The second row shows what the defense buys. In the attack block, the inflated price lasted zero seconds, so it weighs zero in the average. The third shows what it does not buy. In this scenario, an account with its own funds buys the BAR, waits one block, and the oracle reads at the next block. The rigged price then counts for 12 seconds out of 720: (12 × 998 + 708 × 0.1) / 720 ≈ 16.73. The spot price had been multiplied by nearly 10,000. Diluted in the average, it still weighs 167 times the true price.
For his price to count, the attacker must therefore leave it in place until the next block. But a flash swap is repaid in the same transaction. He needs his own funds, as in the test, and enough BAR as collateral. Above all, he leaves his purchase exposed to arbitrageurs, those bots that bring a price back as soon as it drifts from the market. Each BAR deposited still lets him borrow about 13 WETH, while it is worth 0.1. The average makes the attack expensive, not impossible.
Another gap with the chain: in the POC, the three pools live in the same database, so one transaction crosses them effortlessly. On Ethereum, the transaction crosses contracts written by teams that do not know each other. In SQL, all those teams would have to share the same database, hence the same operator.
Who goes first? In a database it is an accident, on chain it is a market
Let us replay a classic database mistake. For this, the test defines a deliberately faulty function, echanger_naif. It reads the pool's reserves, computes its swap on them, then writes the reserves it computed. The pool holds 5 tokens A and 10 tokens B. Alice reads these reserves and brings 1 A. Meanwhile, Bob brings 2 A and his swap finishes. Alice then writes the reserves she computed on 5 and 10:
Both swaps were paid at the starting price. After Bob's, the pool held 7.15 B, fees included. The recorded reserves say 6 A and 8.34 B. The actual balance holds 8 A and 5.49 B. Their product is 43.9, about 12.2% below the K of 50. This is the lost update. PostgreSQL lets it through in its default mode, READ COMMITTED. This isolation level sets what a transaction sees of the others' writes. It does not stop two sessions from reading the same row before writing.
The fix is well known: a lock. The real echanger() starts with SELECT … FOR UPDATE on the pool row, which reserves it until the end of the transaction. In READ COMMITTED, Bob waits for Alice to finish, then computes on the reserves she left. In REPEATABLE READ, each transaction keeps the view of the database taken at its start. Bob then gets a serialization error and must replay his swap.
The K check offers a second safety net. The real echanger() recomputes it on the actual balance, not on the recorded reserves. Without the lock, the second swap is therefore refused, not lost: the mutation that removes the lock shows it. With the lock, it succeeds. Only echanger_naif, which has no such check, loses the swap silently.
A lock protects only the rows it takes. In REPEATABLE READ, a row that is only read comes from the view taken at the start of the transaction. In the POC, the block time is such a row: it could be stale without any error signaling it. A code review found three holes of this kind. The functions now lock what they read too, with FOR SHARE, and the repository README gives the details.
On Ethereum, this problem does not exist: the transactions of a block really run one after the other. The order, though, becomes a stake. Before entering a block, a transaction often waits in a public queue, the mempool. Whoever builds the block chooses the order, and you can pay to go ahead of the others.
Hence the sandwich: a bot sees your purchase in the queue, buys just before to push the price up, and sells right after. In the test, the pool holds 1,000 T0 tokens and 1,000 T1 tokens, and the victim brings 100 T0. The bot brings 200 before her. She receives 63.96 T1 instead of 90.66, which is 29.5% less.
The protection is called the minimum accepted, a parameter the book explains: if the victim receives less, her transaction fails. With a minimum 1% below the expected amount, the big sandwich of the test makes the victim's transaction fail. A bot that calibrates its move buys just enough for the victim to receive exactly her minimum. It still earns 1.06 T0, before the gas fees of its transactions. The minimum caps the loss, it does not remove the sandwich.
In a database, order is an accident you tame with a lock. On chain, it is a market. The guardrail that is up to you is the minimum accepted: you write down what you refuse to lose.
What SQL will not replay: someone is always left to trust
The POC protects its tables seriously. Users have no direct write rights: they go through functions like echanger(), which run with the rights of their owner. The test checks it: UPDATE pool SET reserve0 = 0, run by alice (a test user), is refused, while echanger() goes through. Then the test switches back to superuser, and a direct UPDATE on the same table goes through.
That is the basic difference. The operator, whoever runs the database, holds the superuser. They can rewrite a balance, disable the flash swap trigger or restore yesterday's backup. SQL rights protect users from each other, never from the operator. So you trust the operator, as you trust your bank.
| Question | PostgreSQL | Ethereum |
|---|---|---|
| Who can write outside the rules? | The superuser | Nobody, except what the contract allows |
| Who can call? | Those who have an account | Anyone |
| Who can verify the state? | The operator, and those they let read | Anyone who runs a node |
| Who chooses the order? | The locks, by luck of arrival | Whoever builds the block |
| Who pays for the computation? | The operator | The caller, in gas |
The right column needs two caveats. First, "nobody, except what the contract allows". The code of Uniswap v2's pools can no longer be modified, but a protocol can keep an admin key. The book points this out: a DeFi project can remain centralized as long as its contract keeps an owner. That account keeps control.
Second, "anyone who runs a node", a computer that holds its own copy of the chain. In practice, many applications trust a node provider rather than recompute everything.
This guarantee has a price, and that price is slowness. Every node reruns every transaction, so that nobody has to trust the one who wrote it. A failed transaction even stays recorded in the block and pays its gas, the computation fee. A ROLLBACK, by contrast, leaves nothing visible in the tables.
My take: SQL replays the arithmetic of DeFi, not its guarantee. A blockchain is not a slow database, and a database is not a fast blockchain. They are two answers to two different questions. If everyone who uses it accepts trusting the same operator, take PostgreSQL: no gas to pay, no block to wait for. The chain earns its price when they cannot name anyone to trust. Even then, look at who holds a key on the contract: the guarantee stops where the code hands control to someone.
Conclusion
A share value that moves in place of a thousand balances: the question started from this likeness with a database. The likeness holds to the end of the math, with UPDATEs, views and a trigger that waits for the COMMIT. The two math traps found along the way are in PostgreSQL: / and sqrt() round.
Writing DeFi in SQL does not make the blockchain useless. It shows where it is useful. Not in the math, which PostgreSQL replays easily, but in the absence of anyone who could rewrite it.
The books behind this article
Building Full Stack DeFi ApplicationsReused: the swap and lending pools, the rate, the liquidation and the oracle attack. To correct: the book gives the same value to the borrowing cap and the liquidation threshold, which Aave distinguishes. The POC adds an average price case, the book's defense: a rigged price held until the next block still gets through.
Sources
Documentation consulted on November 24, 2026:
- The calculation of the amount returned:
UniswapV2Library.sol, Uniswap v2 periphery. - The K check, the flash swap, the shares and the cumulative price:
UniswapV2Pair.sol, Uniswap v2 core. - The reference test cases:
UniswapV2Pair.spec.ts. - Deferred triggers: CREATE TRIGGER, PostgreSQL 18 documentation.
- Isolation levels: Transaction Isolation, PostgreSQL 18 documentation.
- The
numerictype and thedivfunction: Numeric Types and Mathematical Functions. - The cumulative average price of Uniswap v2: Oracles, Uniswap documentation.
- The Aave v2 thresholds:
reservesConfigs.ts(ETH borrowing cap and liquidation threshold) andrateStrategies.ts(optimal utilization), Aave protocol-v2 project. - Gas, blocks and transaction order: Gas, Blocks and MEV, ethereum.org documentation.