Skip to main content

Overview

The most comprehensive template. Includes a Uniswap-style AMM (Factory, Pair, Router), a collateralized lending vault, Synthetix-style staking rewards, and a price oracle. Comes with IPFS, a subgraph indexer, Blockscout explorer, and Chainlink mock oracle as services.
DifficultyAdvanced
CategoryDeFi
ChainsEthereum
ServicesIPFS, Subgraph, Blockscout, Chainlink Mock
LicenseApache-2.0

Quick Start

dokrypt init my-defi --template evm-defi
cd my-defi
dokrypt up
# ✓ ethereum    http://localhost:8545
# ✓ ipfs        http://localhost:5001
# ✓ blockscout  http://localhost:4000
# ✓ oracle      chainlink-mock

Generated Files

my-defi
dokrypt.yaml
foundry.toml
README.md
contracts
token
DeFiToken.sol
amm
Factory.sol
Pair.sol
Router.sol
lending
LendingVault.sol
InterestModel.sol
staking
StakingRewards.sol
oracle
PriceOracle.sol
test
amm
Factory.t.sol
Router.t.sol
lending
LendingVault.t.sol
staking
StakingRewards.t.sol
scripts
deploy-amm.js
deploy-lending.js
deploy-staking.js

Contracts

DeFiToken.sol

ERC-20 with governance delegation, minting, and burning. Constructor:
constructor(string memory name, string memory symbol, uint256 initialSupply)
FunctionAccessDescription
Standard ERC-20Publictransfer, approve, transferFrom
mint(to, amount)OwnerMint new tokens
burn(amount)PublicBurn your tokens
delegate(delegatee)PublicDelegate voting power

AMM Module

A Uniswap V2-style automated market maker with three contracts.

Factory.sol

Creates and tracks liquidity pairs using CREATE2 for deterministic addresses.
FunctionAccessDescription
createPair(tokenA, tokenB)PublicDeploy a new pair contract
computePairAddress(tokenA, tokenB)ViewPredict pair address before creation
allPairsLength()ViewTotal number of pairs
setFeeTo(newFeeTo)OwnerSet fee recipient
Uses CREATE2 with salt keccak256(abi.encodePacked(token0, token1)).

Pair.sol

Liquidity pool implementing the x * y = k constant product invariant. Key Constants:
  • MINIMUM_LIQUIDITY = 1000 — Permanently locked on first mint
  • SWAP_FEE = 3 — 0.3% swap fee (3/1000)
FunctionAccessDescription
initialize(token0, token1)FactoryOne-time pair setup
mint(to)PublicAdd liquidity, receive LP tokens
burn(to)PublicRemove liquidity, burn LP tokens
swap(amountOut0, amountOut1, to)PublicSwap tokens (constant product enforced)
skim(to)PublicWithdraw excess tokens
sync()PublicSync reserves to actual balances
Features:
  • ERC-20 LP tokens for liquidity providers
  • TWAP (Time-Weighted Average Price) oracle via price0CumulativeLast and price1CumulativeLast
  • Flash swap support
Events: Mint, Burn, Swap, Sync

Router.sol

High-level interface with deadline protection and slippage guards.
FunctionAccessDescription
addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline)PublicProvide liquidity with slippage protection
removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline)PublicRemove liquidity
swapExactTokensForTokens(amountIn, amountOutMin, path[], to, deadline)PublicSwap with exact input
swapTokensForExactTokens(amountOut, amountInMax, path[], to, deadline)PublicSwap with exact output
All functions have deadline parameter — reverts if block.timestamp > deadline. Events: LiquidityAdded, LiquidityRemoved, SwapExecuted

LendingVault.sol

Collateralized lending with liquidation mechanics. Constants:
ConstantValueDescription
COLLATERAL_FACTOR75% (7500 bp)Max borrow relative to collateral
LIQUIDATION_THRESHOLD80% (8000 bp)Position becomes liquidatable
LIQUIDATION_BONUS105% (10500 bp)5% bonus for liquidators
Functions:
FunctionAccessDescription
depositCollateral(token, amount)PublicDeposit collateral
withdrawCollateral(token, amount)PublicWithdraw collateral (health check)
borrow(amount)PublicBorrow against collateral
repay(amount)PublicRepay debt
liquidate(borrower, collateralToken, debtRepaid)PublicLiquidate unhealthy position
addCollateral(token)OwnerAdd supported collateral type
accrueInterest()PublicUpdate interest accrual
getUserHealthFactor(user)ViewCheck position health
isLiquidationEligible(user)ViewCheck if liquidatable
getMaxBorrowable(user)ViewMax borrow amount
Liquidation Flow:
  1. Borrower’s health factor drops below threshold (collateral value / debt > 80%)
  2. Liquidator calls liquidate() with the debt amount to repay
  3. Liquidator receives collateral worth 105% of repaid debt (5% bonus)
  4. Borrower’s debt and collateral are reduced accordingly
Events: CollateralDeposited, CollateralWithdrawn, Borrowed, Repaid, Liquidated, InterestAccrued

InterestModel.sol

Kinked linear interest rate model. Rates increase slowly at low utilization and steeply at high utilization.
FunctionAccessDescription
calculateInterestRate(totalBorrowed, totalAvailable)ViewReturns annual interest rate

StakingRewards.sol

Same Synthetix-style staking as the evm-token template. See evm-token StakeRewards for full details.

PriceOracle.sol

Simple owner-managed price feed for the lending vault.
FunctionAccessDescription
setPrice(token, price)OwnerSet token price
setPrices(tokens[], prices[])OwnerBatch update prices
getPrice(token)ViewGet current price
isPriceStale(token)ViewCheck if price is > 1 hour old

Deployment

Deploy AMM

npx hardhat run scripts/deploy-amm.js --network localhost
Deploys Factory, Router, test tokens, creates a pair, and adds initial liquidity.

Deploy Lending

npx hardhat run scripts/deploy-lending.js --network localhost
Deploys borrow token (USDT), collateral token (WETH), InterestModel, PriceOracle, and LendingVault. Configures prices, adds collateral support, and supplies initial tokens.

Deploy Staking

npx hardhat run scripts/deploy-staking.js --network localhost
Deploys staking and reward tokens, StakingRewards contract, transfers reward funds, sets duration, and notifies the contract.

Testing Workflows

AMM Testing

# Start environment
dokrypt up

# Deploy AMM
npx hardhat run scripts/deploy-amm.js --network localhost

# Test swaps, liquidity operations
dokrypt test run --filter "amm"

Lending Testing with Price Manipulation

# Deploy lending vault
npx hardhat run scripts/deploy-lending.js --network localhost

# Deposit collateral and borrow
# Then manipulate oracle price to test liquidations

# Run lending tests
dokrypt test run --filter "lending"

Staking with Time Travel

# Deploy staking
npx hardhat run scripts/deploy-staking.js --network localhost

# Stake tokens, then fast-forward time
dokrypt chain time-travel 30d

# Check accumulated rewards
dokrypt test run --filter "staking"