Book a free call

How Smart Contracts Power DeFi: Lending, Swaps and More

Smart contracts run DeFi by holding funds and setting the rules for lending, swaps and staking, so every deal follows code instead of a clerk.

Hertiv engineering teamReviewed by a senior engineer
7 min read
How Smart Contracts Power DeFi: Lending, Swaps and More
On this page

Short answer

Smart contracts run DeFi by holding user funds and enforcing the rules of each financial service in code. Lending pools use contracts to set interest and demand collateral, exchanges use them to swap tokens at a formula price, and staking contracts distribute rewards. No bank or broker sits in the middle: the contract checks the conditions, moves the funds and records the result.

What does it mean that smart contracts run DeFi?

Smart contracts run DeFi by holding the money and the rules of a financial service in code on a blockchain, instead of in a bank's systems. When you lend, swap or stake in DeFi, you send funds to a contract, and the contract decides what happens next based on its code.

The contract is the counterparty. In a traditional loan, a bank checks your credit, holds your collateral and chases repayment. In DeFi, a contract checks the collateral value, releases the loan, charges interest and sells the collateral if its value falls too far. Nobody approves the loan by hand.

This is why DeFi can run without accounts or opening hours. Anyone with a wallet can call the contract, and the contract treats every caller the same way. The trade-off is that the code is final: if the contract has a bug, or the rules are misunderstood, there is no clerk to call and no reversal button.

How do smart contracts run lending and borrowing?

Smart contracts run lending by pooling deposits, setting interest from supply and demand, and requiring collateral before any loan is released.

A lending pool is a contract that holds deposits from lenders and loans from borrowers. Lenders deposit tokens and receive a receipt token that grows in value as interest accrues. Borrowers deposit collateral worth more than the loan, and the contract releases the borrowed tokens only when the collateral is locked.

Interest is set by the contract, not by a committee. When many people want to borrow and few are lending, the rate rises; when the pool is full of deposits, the rate falls. The rate updates with every deposit and withdrawal, so it tracks the market in real time.

StepWhat the contract doesWho it affects
DepositTakes tokens, issues a receipt tokenLenders
Collateral lockHolds collateral worth more than the loanBorrowers
Loan releaseSends borrowed tokens to the borrowerBorrowers
Interest accrualRates update with supply and demandBoth sides
RepaymentReturns collateral when the loan is paidBorrowers
LiquidationSells collateral if its value falls too farBorrowers

The liquidation step is the safety valve. If collateral falls below the required ratio, anyone can call the contract to sell it and repay the loan, which keeps the pool whole. For the wider picture of building these products, DeFi development use cases covers how teams design them.

How do smart contracts run token swaps?

Smart contracts run token swaps through automated market makers, which price trades with a formula instead of matching buyers and sellers.

A swap pool holds two tokens, and the contract sets the price from the ratio of the two balances. When you swap token A for token B, you add A to the pool and take B out, which shifts the ratio and moves the price. Large trades move the price more, which is why big swaps cost more than small ones.

Liquidity providers supply both tokens to the pool and earn a share of the trading fees. The contract tracks each provider's share and pays out fees in proportion. When a provider withdraws, the contract returns their share of both tokens plus the fees earned.

The contract also guards the trade. It checks that the price has not moved too far since the user quoted it, and it cancels the swap if the move is beyond the limit the user set. This slippage check is what stops a trade from executing at a price the user never agreed to.

How do staking and yield contracts work?

Staking and yield contracts lock tokens, track who locked what and for how long, and distribute rewards in proportion to each share.

A staking contract takes your tokens and records your deposit, the time it arrived and the share of the pool it represents. Rewards arrive on a schedule set by the contract, and each staker's share grows in line with their deposit. When you withdraw, the contract returns your tokens plus the rewards earned.

Yield farming stacks contracts together. A user deposits tokens in one contract, receives a receipt token, deposits that receipt in a second contract, and earns rewards from both. Each contract only knows its own step, so the chain of contracts has to be understood as a whole before anyone deposits.

The risk is that rewards are often paid in a token whose price can fall. A contract that promises a high annual rate in its own token may pay less in real terms if the token loses value, so the rate on the screen is not the return in your pocket.

What happens when a loan goes wrong?

When a DeFi loan goes wrong, the contract sells the collateral, repays the lender and keeps whatever is left for the borrower, all without a human decision.

The trigger is the collateral ratio. A borrower who takes a loan against collateral worth 150% of the loan is safe while the ratio holds, but if the collateral price falls and the ratio drops below the contract's limit, the loan becomes eligible for liquidation.

Liquidation is open to anyone. A liquidator calls the contract, repays part of the loan and buys the collateral at a discount. The discount is the incentive that keeps liquidators watching, and it is also the cost the borrower pays for letting the ratio slip.

The contract learns prices from oracles, which feed market prices onto the chain. If an oracle reports a wrong price, the contract acts on it, so the quality of the price feed matters as much as the contract code. A single bad price can trigger liquidations that should never have happened.

How to check a DeFi contract before you use it

You check a DeFi contract before using it by reading its audit, its rules and its history, and by starting with a small amount you can afford to lose.

  1. Find the audit. Look for a public audit by a known firm, and read what it found, not just that it exists. An audit with unresolved critical findings is a warning sign.
  2. Read the rules. Check the collateral ratio, the liquidation discount, the fees and the withdrawal terms. If you cannot find them in plain language, do not deposit.
  3. Check who can change the contract. Some contracts can be upgraded by their owners. If one key or one team can change the rules, the trust is in them, not in the code.
  4. Look at the history. A contract that has held large funds for a long time without incident is safer than a new one with the same code. Age and size are weak signals, but they are signals.
  5. Test with a small amount. Deposit a small sum, try a withdrawal, and confirm the process works before you commit more. A contract that blocks withdrawals is a contract to leave.
  6. Check the price feed. Find out which oracle the contract uses and whether it has a fallback. A single price source is a single point of failure.

Smart contracts are the building blocks, and how smart contracts work explains their mechanics in more depth.

Example (hypothetical): a lending pool with 100 lenders

Example (hypothetical): a lending pool holds deposits from 100 lenders, each depositing $1,000, so the pool holds $100,000. A borrower deposits collateral worth $60,000 and borrows $40,000, which is a 150% collateral ratio.

Over a year the loan earns 10% interest, which is $4,000. The pool keeps 10% of that as a fee, which is $400, leaving $3,600 for the lenders. Split across 100 lenders, that is $36 each for the year on a $1,000 deposit, or 3.6% before any losses.

Now suppose the collateral falls in value to $55,000. The ratio is still above the contract's 130% limit, so nothing happens. If it falls to $50,000, the ratio drops below the limit and a liquidator repays part of the loan, buys collateral at a discount, and the pool is made whole. The arithmetic is simple; the risk is in the price moves, not the maths.

What are the common mistakes?

The most common smart contract DeFi mistakes are trusting an unaudited contract, ignoring the oracle, and borrowing at the maximum ratio.

  • Skipping the audit check. An unaudited contract holding user funds is a warning sign. Read the audit, including the findings the team has not fixed.
  • Borrowing at the maximum ratio. A loan at the edge of the limit liquidates on a small price move. Leave a buffer so normal volatility does not trigger a sale.
  • Ignoring the oracle. The contract trusts its price feed. A thin or single-source feed can report a wrong price and trigger liquidations.
  • Chasing the highest yield. The highest rate usually comes with the newest token or the thinnest pool. High rates paid in a falling token are not high returns.
  • Stacking contracts blindly. Yield farming chains several contracts together. Each extra contract is an extra place for a bug or a bad price.
  • Forgetting the fees. Network fees on deposits, swaps and withdrawals add up, especially on small amounts. Check the fee on every step, not just the headline rate.

For decentralised trading specifically, what is a DEX covers how exchanges run without an order book.

Key takeaways

  • Smart contracts hold the funds and enforce the rules; no bank sits in the middle
  • Lending pools set interest from supply and demand and require over-collateral
  • Swaps price trades from the ratio of tokens in the pool, not an order book
  • Liquidation keeps pools whole, but it is triggered by the oracle price
  • Check the audit, the upgrade keys and the price feed before depositing

Frequently asked questions

What is a smart contract in DeFi?

A smart contract in DeFi is code on a blockchain that holds funds and enforces the rules of a financial service, such as who can borrow, at what rate, and what happens if collateral falls in value. Users interact with the contract directly, and the contract executes the rules without a bank or broker.

Do smart contracts replace banks in DeFi?

They replace the bank's role of holding funds and enforcing rules, but they do not replace everything a bank does. There is no credit check, no customer service desk and no reversal if a transaction goes wrong, so users take on more responsibility for checking the contract first.

How do DeFi lending pools set interest rates?

The contract sets the rate from supply and demand: when many people want to borrow and few are lending, the rate rises, and when the pool is full of deposits, the rate falls. The rate updates with every deposit and withdrawal, so it tracks the market in real time.

What is liquidation in DeFi lending?

Liquidation is when the contract sells a borrower's collateral because its value fell below the required ratio. Anyone can call the contract to repay part of the loan and buy the collateral at a discount, which keeps the pool whole and gives liquidators an incentive to act.

Are smart contracts in DeFi safe?

They are as safe as their code, their audit and their price feed. A contract that has been audited, has held large funds for a long time and uses a reliable oracle is safer than a new unaudited one, but no contract is risk-free, so start with a small amount.

Can a smart contract be changed after launch?

Some can. Contracts with upgrade keys or admin controls can be changed by their owners, which means the trust is partly in the team, not only in the code. Check who holds the keys and what they can change before you deposit.

Found this useful? Share it.
Hertiv engineering team

Written from projects we build for clients: blockchain systems in production. Every post is reviewed by a senior engineer before publishing and updated when practice changes.

About HertivHow we work

Building a DeFi product and need smart contracts your users can trust? Talk to Hertiv.

A senior engineer replies within one business day. Or see our DeFi Development service.

Book a free call

Keep reading

All posts

Tell us what you want to build

A senior engineer reads every request and replies within one business day with questions, a rough range, or a call link.

  • NDA on request before any details
  • You own all code, models and IP
  • US, UK and EU time-zone overlap

Your email app should open with your message ready to send. If it does not, write to contact@hertiv.com.

Prefer email? Write to contact@hertiv.com
Estimate costBook a call