Imagine: your stablecoin XUSD is trading at $1.05 on Uniswap, and the team can do nothing — market makers haven't arrived, liquidity is low. Depegging by 5% within an hour after launch. Without PSM (Peg Stability Module) this is inevitable. PSM is a smart contract that creates a built-in arbitrage mechanism, automatically maintaining the peg. We design and develop PSM tailored to your tokenomics, considering liquidity, and simulate behavior in stress scenarios.
The Math of Stabilization and Points of Failure
How the PSM Arbitrage Mechanism Works
Suppose your stablecoin XUSD trades at $1.02 on a DEX. PSM offers: bring $1 in USDC, get 1 XUSD (minus tin — fee on entry, e.g., 0.1%). An arbitrageur deposits 1000 USDC, receives 999 XUSD, sells them on Uniswap at $1.02, getting $1019.98. Profit $19.98 minus gas. After enough such trades, XUSD supply on the market increases, price drops to $1.00.
Reverse situation: XUSD = $0.98. PSM: bring 1 XUSD, get $1 USDC (minus tout — fee on exit). Arbitrageur buys 1000 XUSD for $980 on Uniswap, deposits into PSM, receives $999 USDC. Profit $19 minus gas. XUSD is bought off the market, price rises.
Key parameter — PSM debt ceiling. Without a ceiling, PSM can accumulate 100% reserves in one asset (e.g., USDC) — this concentrates regulator risk (Circle can freeze USDC). MakerDAO at its peak held over 50% of DAI reserves in USDC via PSM, leading to parameter revision after regulatory threats. Source: MakerDAO Governance
Attack Through Unbalanced PSM
If tin/tout is set too low (< 0.01%), PSM becomes a free arbitrage tool that drains reserves at any market shock. At XUSD = $0.995, arbitrage becomes profitable for volumes from $50K — MEV bots activate automatically.
Optimal tin/tout range for a new stablecoin at launch: 0.1–0.5%. As liquidity grows, reduce to 0.01–0.1%. These are configurable parameters that governance can change via timelock.
PSM Contract Architecture
Core Module Functions
// Entry: user deposits collateral, receives stablecoin
function sellGem(address usr, uint256 gemAmt) external {
uint256 gemAmt18 = gemAmt * (10 ** (18 - dec)); // normalize decimals
uint256 daiAmt = gemAmt18; // 1:1 before fee
uint256 fee = daiAmt * tin / WAD; // tin in WAD (1e18)
require(dai.balanceOf(address(this)) >= daiAmt - fee, "PSM/insufficient-dai");
vow.bump(fee); // fee to treasury
gem.transferFrom(msg.sender, address(this), gemAmt);
dai.transfer(usr, daiAmt - fee);
emit SellGem(usr, gemAmt, fee);
}
// Exit: user deposits stablecoin, receives collateral
function buyGem(address usr, uint256 gemAmt) external {
uint256 gemAmt18 = gemAmt * (10 ** (18 - dec));
uint256 daiAmt = gemAmt18;
uint256 fee = daiAmt * tout / WAD;
require(gem.balanceOf(address(this)) >= gemAmt, "PSM/insufficient-gem");
dai.transferFrom(msg.sender, address(this), daiAmt + fee);
vow.bump(fee);
gem.transfer(usr, gemAmt);
emit BuyGem(usr, gemAmt, fee);
}
Critical point — decimals normalization. USDC has 6 decimals, most stablecoins have 18. Without gemAmt * (10 ** (18 - dec)), PSM arithmetic breaks — user gets 10^12 times fewer tokens. Even experienced developers make decimals errors when dealing with non-standard ERC-20.
Collateral Whitelist and Multi-Asset PSM
Basic PSM works with one collateral. An extended version supports multiple: USDC, USDT, DAI — each with its own tin/tout and debt ceiling parameters.
Adding new collateral via governance: addGem(address gemAddress, uint256 ceiling) with a minimum 48-hour timelock. This prevents adding a malicious ERC-20 with custom transferFrom that drains PSM through reentrancy.
How RateLimiter Protects PSM from Flash Loan Attacks
Flash loan attack on PSM: borrow USDC, dump into PSM via sellGem, get XUSD, sell on market, create artificial price pressure, buy XUSD back cheaper, return to PSM, repay flash loan with profit. To neutralize — RateLimiter: maximum operation volume in PSM over N blocks.
mapping(uint256 => uint256) public volumePerBlock;
uint256 public constant MAX_VOLUME_PER_WINDOW = 1_000_000e18; // 1M stablecoins
uint256 public constant WINDOW_BLOCKS = 50; // ~10 minutes
function _checkRateLimit(uint256 amount) internal {
uint256 windowStart = block.number - (block.number % WINDOW_BLOCKS);
volumePerBlock[windowStart] += amount;
require(volumePerBlock[windowStart] <= MAX_VOLUME_PER_WINDOW, "PSM/rate-limit");
}
Governance and Parameter Management
Which PSM Parameters Are Critical for Security?
PSM without governance is a static tool. PSM with governance is a living market mechanism. Parameters that must be in governance:
| Parameter |
Description |
Recommended Timelock |
tin |
Fee on entry |
24 hours |
tout |
Fee on exit |
24 hours |
line (debt ceiling) |
Max volume |
48 hours |
addGem |
New collateral |
72 hours |
pause |
Halt PSM |
0 (emergency) |
For new protocols, we recommend Gnosis Safe + OpenZeppelin TimelockController. Pause is the only operation without timelock but requires a multisig (minimum 3/5).
Process of Work
Analysis and simulation (2–3 days). Python script simulates PSM behavior under different volatility scenarios: peg deviation 1%, 3%, 5%, flash crash. We select optimal tin/tout and debt ceiling. Analyze target stablecoin liquidity on DEX — this determines minimum PSM size.
Development (4–6 days). Core PSM contract, RateLimiter, multi-asset support if needed, governance integration. Foundry tests: unit tests for all functions, fuzz tests for edge-case decimals and amounts, fork tests with real USDC/USDT.
Audit (2–3 days). Slither, manual review of decimals handling and overflow/underflow (critical for Solidity < 0.8.0; in 0.8+ SafeMath is built-in, but custom unchecked blocks require attention).
Deployment (1–2 days). Testnet first, mainnet via multisig with verification.
Basic PSM with one collateral — 1–1.5 weeks. With multi-asset support, governance, and dashboard — 2–3 weeks. Cost is calculated individually after tokenomics analysis.
Typical PSM Development Mistakes
- Incorrect decimals normalization — one of the most common and dangerous.
- Missing rate limiter — PSM becomes vulnerable to flash loan attacks.
- Too low tin/tout — arbitrage becomes ineffective, PSM can be drained.
- Too high debt ceiling — concentrates centralization risk of reserves.
What You Get
Upon completion, you receive:
- PSM contract source code with comments
- Audit report (Slither + manual code review)
- Technical documentation for deployment and management
- Multisig contracts (Gnosis Safe + TimelockController)
- Operations manual for your team
- Technical support for 14 days after deployment
Our experience: over 10 years in DeFi, 15+ launched stablecoins, 5 years in blockchain development. We guarantee stable PSM operation and adherence to best security practices.
Order PSM development — contact us for a consultation and project evaluation. Get a free engineer consultation.
DeFi Protocol Development
We design modular DeFi protocols where the math of stablecoins, liquidity, and oracles works flawlessly. Mango Markets is a stress test: the attacker manipulated the spot price through a single account, took a loan against inflated collateral, and withdrew $114 million. The oracle took the price from a single source without TWAP. Not a code bug—it was an architectural decision that became a vulnerability. Our experience shows: any DeFi protocol is a system of bets that all components, from calculations to economic incentives, are correctly aligned simultaneously.
We don't write code under the 'if it works, don't touch it' mindset. We model stress scenarios: cascading liquidations, depegs, flash loans. Only then do we build events that won't break the protocol.
Why are oracles a critical component of DeFi?
Most major DeFi hacks started with oracle manipulation. Let's break down the three layers we use in every project.
Spot price as oracle—not an option. Uniswap v2 spot price can be shifted by a flash loan in one transaction. The price at the end of the block is the only one that enters the state, and the oracle reads it. Attack scheme: borrow via flash loan → buy asset into the pool → price rises → take a loan against inflated collateral → sell asset → repay flash loan. One transaction.
TWAP as protection. Uniswap v3 observe() averages the price over a period (30 minutes). Manipulation requires maintaining the price for several blocks—this is expensive. But TWAP reacts slowly to legitimate changes, opening a window for arbitrage on liquidation during sharp movements.
Chainlink Price Feeds are an aggregation from multiple data providers with a median. Standard for lending. Problem: heartbeat 1–24 hours and deviation threshold 0.5%. If the price doesn't move, the feed may not update for a day. In volatile markets—lag.
| Oracle |
Mechanism |
Manipulation Protection |
Latency |
| Chainlink |
Median from independent providers |
High (decentralization) |
Up to 24h at 0% movement |
| Uniswap v3 TWAP |
Average price over N blocks |
High (hard to maintain) |
30 min – 1 h |
| Pyth Network |
Cross-chain low-latency |
Medium (dependent on publisher) |
Seconds |
In production, we use a two-tier check: Chainlink aggregator + Uniswap v3 TWAP as a verifier. If the discrepancy exceeds N%, the transaction is rejected and the system is paused.
How to protect a DeFi protocol from flash loan attacks?
Flash loans turn any user into an owner of unlimited capital for one transaction. Therefore, when designing contracts, we assume: everyone has access to unlimited capital. This completely changes the threat model.
Legitimate uses of flash loans are arbitrage, liquidation, and self-liquidation. But the protocol must verify that the loan is not used for manipulation: the oracle must not read the price from a pool that can be shifted in one transaction. We add checks on block.timestamp and minimum liquidity depth.
Key Components of DeFi Architecture
| Protocol Type |
Core Mechanism |
Main Risk |
| DEX (AMM) |
x*y=k or concentrated liquidity |
impermanent loss, oracle manipulation |
| Lending |
collateral ratio, liquidation |
bad debt during cascading liquidations |
| Yield aggregator |
auto-compounding strategies |
rug via strategy upgrade |
| Derivatives / Perps |
funding rate, mark price |
liquidation cascades, socialized losses |
| Liquid staking |
stETH-style rebasing |
depegging on mass unstake |
AMM: From x*y=k to Concentrated Liquidity
Uniswap v2 uses x * y = k. LP tokens are ERC-20—each pool issues its own token proportional to the share. Problem: liquidity is spread across the entire curve, most of it unused.
Uniswap v3 and ERC-721 positions: concentrated liquidity—LPs provide liquidity in a range [priceLow, priceHigh]. Capital efficiency up to 4000x for stable pairs. But ERC-721 breaks vault strategies built for ERC-20. Range management is a separate engineering challenge: a position falls out of range when the price moves, stops earning fees, and becomes single-asset. Protocols like Arrakis Finance automatically rebalance. If you build a vault on top of v3, you need your own range manager or integration with an existing one.
Slippage in v3 is calculated via sqrtPriceX96—96-bit fixed-point math. Errors on the frontend lead to discrepancies between visible and actual slippage.
Curve for pairs with close prices (stablecoin/stablecoin, stETH/ETH) uses an invariant combining constant product and constant sum. Lower slippage within the peg range. Contracts are in Vyper, code is mathematically dense, auditing is difficult.
Lending Protocols: Collateral, Liquidation, Bad Debt
LTV defines the maximum loan against collateral. Liquidation threshold is the level for liquidation. The difference is the buffer for the liquidator. Typical example: LTV 75%, liquidation threshold 80%, bonus 5%. If the price drops 20%+, the position is open for liquidation.
Cascading liquidations: many positions are liquidated simultaneously → liquidators sell collateral → price drops → next wave. LUNA/UST 2022 is a classic cascade.
If collateral devalues faster than liquidation, the protocol incurs bad debt. Aave uses a Safety Module (staked AAVE), Compound uses reserves. Without a backstop, bad debt is socialized via dilution of the supply token or netting.
Designing a liquidation system requires modeling stress scenarios: a single liquidation bot failure, high gas, collateral delisting.
Yield Farming and Incentive Mechanics
Liquidity mining distributes governance tokens to LP providers. Problem: mercenary capital—farmers come, sell tokens, leave. TVL is illusory.
Sustainable mechanics: protocol-owned liquidity (Olympus bonding), veToken (CRV locked → boost + governance), locked staking with penalty. The ve-model, if implemented incorrectly, creates governance concentration. A timelock on gauge weight changes and limits on voting power are needed.
What Our DeFi Protocol Development Includes
- Architectural documentation: contract interaction diagrams, liquidation stress tests, oracle calculations.
- Implementation in Solidity 0.8.x with OpenZeppelin 5.x (AccessControl, ReentrancyGuard, Pausable, TimelockController) and Solmate for gas-optimized base contracts.
- Foundry fork tests on real mainnet (Uniswap, Chainlink, Aave) — pre-deployment tests cover all scenarios.
- Audit: at least two independent auditors for TVL over $1M. Code4rena or Sherlock for bug bounty.
- Deployment with Gnosis Safe 3/5 multisig + timelock 48–72 hours.
- Monitoring via Tenderly (alerts, simulations), OpenZeppelin Defender (automation), Forta (on-chain threat detection).
- Post-launch support: updates, patches, upgrades via proxy.
Our Expertise and Experience
We have been developing DeFi protocols since 2020, delivering 30+ projects with a combined TVL of over $150 million. Our clients include protocols in the top 20 by TVL on Ethereum, Arbitrum, and Base. The team consists of certified Solidity developers who have completed ConsenSys Diligence audit tracks.
DeFi basic principles that we apply in practice.
Timelines
- DEX with AMM (Uniswap v2 fork): 6–10 weeks
- Lending protocol (Aave-style, single collateral): 3–5 months
- Yield aggregator with multiple strategies: 2–4 months
- Full-fledged DeFi protocol with governance: 5–8 months including audit
Cost is calculated individually—contact us for a project estimate.
Get a consultation on DeFi protocol architecture—we will analyze the risks and propose an optimal solution.