DeFi Service Architecture Notes: The Components from a Product Perspective
Toris's engineering notes on core DeFi components such as DEXs, lending, and staking from a product view, covering Solidity structure, Next.js integration, and security judgment criteria.
Joohwan Yu · Founder, Full Stack Developer
Toris · Published
Contents
Q. How do you build a DeFi service with Next.js and Solidity? You implement the core logic such as DEXs, lending, and staking in smart contracts, and build a user dashboard in Next.js with wallet integration through ethers.js or thirdweb. The key product design judgment is which components to implement yourself and which to delegate to existing protocols.
When designing web products, Toris judges a tech stack not by “can we use it” but by “is there a reason to put it in the product.” The Web3 space is no different. The DEXs, lending, and staking that make up DeFi are each independent financial logic and a smart contract module, and when introducing them into a product I first ask “what value does putting this logic on-chain give users” and “what security and operations burden do we take on in return.”
These notes are an engineering write-up of the core DeFi components Toris uses as a reference when reviewing Web3 products. I check how each component works through Solidity code, and cover the connection points with a Next.js frontend and the security judgment criteria that decide whether to adopt them.
🌟 What Is DeFi?
DeFi (Decentralized Finance) is a system that uses blockchain technology, especially smart contracts, to provide financial services without central intermediaries such as banks and brokerages. From a product perspective, the heart of it is “replacing the intermediary with code,” which also means that all the trust assurance and exception handling the intermediary used to do must now be carried by contract design and verification.
Traditional Finance vs. DeFi
| Item | Traditional finance (CeFi) | Decentralized finance (DeFi) |
|---|---|---|
| Intermediary | Banks, governments, card issuers | Smart contracts (code) |
| Accessibility | KYC/AML, regional/credit limits | Open to anyone (permissionless) |
| Transparency | Limited, internal information | All transactions public (on-chain) |
| Operating hours | Limited to business hours | 24/7, 365 days without interruption |
| Interoperability | Closed systems | Composable like Lego blocks |
Product view: In the table above, the item with the biggest effect on product design is interoperability. Being able to combine existing protocols means you can keep the product’s scope narrow without implementing everything yourself.
🔧 Core DeFi Services and Solidity Code Examples
1. Decentralized Exchange (DEX)
A platform where users swap tokens directly, without a centralized order book. The AMM (Automated Market Maker) model is mainly used. When a product needs token swapping, the first decision point is whether to implement an AMM yourself or integrate an existing DEX. The code below shows the minimum structure needed for that decision: a liquidity pool, swaps, and the pricing formula.
A Simple Uniswap-Style AMM Implementation
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
// A simple DEX contract
contract SimpleDEX is ReentrancyGuard {
IERC20 public immutable tokenA;
IERC20 public immutable tokenB;
uint256 public reserveA;
uint256 public reserveB;
// Track liquidity providers' shares
mapping(address => uint256) public liquidity;
uint256 public totalLiquidity;
// Event definitions
event LiquidityAdded(address indexed provider, uint256 amountA, uint256 amountB);
event TokensSwapped(address indexed trader, address indexed tokenIn, uint256 amountIn, uint256 amountOut);
constructor(address _tokenA, address _tokenB) {
tokenA = IERC20(_tokenA);
tokenB = IERC20(_tokenB);
}
// Add liquidity
function addLiquidity(uint256 _amountA, uint256 _amountB) external nonReentrant {
// ... (omitted)
}
// Token swap (A -> B)
function swapAtoB(uint256 _amountAIn) external nonReentrant {
require(_amountAIn > 0, "Input amount must be positive");
uint256 amountBOut = getAmountOut(_amountAIn, reserveA, reserveB);
require(amountBOut > 0, "Insufficient output");
// Transfer tokens
tokenA.transferFrom(msg.sender, address(this), _amountAIn);
tokenB.transfer(msg.sender, amountBOut);
// Update the liquidity pool
reserveA += _amountAIn;
reserveB -= amountBOut;
emit TokensSwapped(msg.sender, address(tokenA), _amountAIn, amountBOut);
}
// Calculate the amount of tokens to be swapped (x * y = k model)
function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) public pure returns (uint256) {
uint256 amountInWithFee = amountIn * 997; // apply 0.3% fee
uint256 numerator = amountInWithFee * reserveOut;
uint256 denominator = (reserveIn * 1000) + amountInWithFee;
return numerator / denominator;
}
}
Product view: If the swap feature itself is not the product’s differentiator, integrating a proven existing DEX is the choice that reduces both audit cost and the burden of securing liquidity.
2. Lending/Borrowing Protocols
A service where you borrow one cryptocurrency against another as collateral, or deposit your own assets and earn interest. The key design variables are the collateral ratio and the liquidation logic, and these two determine the protocol’s stability.
// A simple lending protocol
contract LendingProtocol is ReentrancyGuard {
// ... (omitted)
// Deposit assets (supply)
function supply(address token, uint256 amount) external nonReentrant {
// ... (omitted)
}
// Collateral-based borrowing
function borrow(address token, uint256 amount) external nonReentrant {
// ... (omitted)
// You must check the collateral ratio with a function like isAccountHealthy(msg.sender)
}
}
Product view: Once lending and borrowing take on a dependency on an oracle that reports collateral prices, the risk surface widens a lot, so for a small team this is the component to judge most carefully before adopting.
3. Staking
A system where you deposit (lock up) a specific token in the protocol and receive rewards in return. It serves roles such as contributing to network security or taking part in governance. Of the three components, its state transitions are the simplest, making it a good starting point to consider when first introducing on-chain logic.
// A simple staking rewards contract
contract StakingRewards is ReentrancyGuard {
// ... (omitted)
// Stake
function stake(uint256 amount) external nonReentrant {
// ... (omitted)
}
// Claim rewards
function getReward() external nonReentrant {
// ... (omitted)
}
}
Product view: For reward calculation, what separates product quality is less the logic itself than the UX problem of “how to show users the deposit period and rate in a predictable way.”
💻 Building a DeFi Dashboard with Next.js
If the contract is the backend, the product users actually meet is the frontend. With Next.js and a library such as ethers.js or thirdweb, you can build a dashboard that interacts with smart contracts in the same development flow as an ordinary web product.
// components/DeFiDashboard.tsx
import { useState } from "react";
import { useContract, useAddress, useContractRead, Web3Button } from "@thirdweb-dev/react";
import { ethers } from "ethers";
export default function DeFiDashboard() {
const address = useAddress();
const [stakingAmount, setStakingAmount] = useState("");
// Create a contract instance with the thirdweb SDK
const { contract: stakingContract } = useContract("YOUR_STAKING_CONTRACT_ADDRESS");
// Read the contract's public variables
const { data: stakedBalance } = useContractRead(stakingContract, "balances", [address]);
const { data: earnedRewards } = useContractRead(stakingContract, "earned", [address]);
return (
<div className="max-w-4xl mx-auto p-4">
<h1 className="text-2xl font-bold mb-6">My DeFi Dashboard</h1>
{/* Staking section */}
<div className="bg-gray-800 rounded-lg p-6 text-white">
<h2 className="text-xl font-semibold mb-4">Staking</h2>
<p>Staked Balance: {stakedBalance ? ethers.utils.formatEther(stakedBalance) : "0"} STK</p>
<p>Rewards: {earnedRewards ? ethers.utils.formatEther(earnedRewards) : "0"} RWD</p>
<input
type="number"
value={stakingAmount}
onChange={(e) => setStakingAmount(e.target.value)}
className="w-full p-2 rounded text-black mt-4"
placeholder="Amount to stake"
/>
{/* Handle the transaction with Web3Button */}
<Web3Button
contractAddress="YOUR_STAKING_CONTRACT_ADDRESS"
action={(contract) => contract.call("stake", [ethers.utils.parseEther(stakingAmount)])}
onSuccess={() => alert("Staking successful!")}
onError={(error) => alert(`Error: ${error.message}`)}
className="w-full bg-blue-500 py-2 rounded mt-2"
>
Stake Now
</Web3Button>
</div>
</div>
);
}
Product view: Wallet connection and the transaction pending state are where a Web3 product loses the most users, so in dashboard design, loading and failure states should be handled far more conservatively than on an ordinary web product.
🔒 Security and Risk Management
Security is the final criterion for whether to adopt a DeFi component. Smart contract bugs, oracle problems, liquidity risk, and the like are hard to fix after deployment, so I use the items below as a design-stage checklist.
- Prevent reentrancy attacks: Use OpenZeppelin’s
ReentrancyGuardor apply the Checks-Effects-Interactions pattern. - Integer overflow/underflow: Use Solidity 0.8.x or later.
- Access control: Use a clear permission management pattern such as
Ownable. - Code audit: Have the smart contract audited by an external specialist firm.
- Testing: Raise test coverage as high as possible to verify edge cases.
If you want to discuss Web3 product design or whether to adopt a DeFi component, please reach out through the Toris contact page.
References
- Solidity official docs: The smart contract language reference and security considerations.
- OpenZeppelin Contracts docs: Proven contract modules such as
ReentrancyGuardandOwnable. - thirdweb official docs: SDK guide for integrating contracts and wallets in Next.js.
Advertisement