DeFi Protocol Templates

Production-ready templates for common DeFi protocols including staking, AMMs, governance, lending, and flash loans

DeFi Protocol Templates

What Is This

DeFi Protocol Templates is a technical skill for the Happycapy Skills platform that provides production-ready smart contract templates for core decentralized finance (DeFi) protocols. These templates cover staking, automated market makers (AMMs), governance systems, lending and borrowing mechanisms, and flash loan support. The skill is designed to accelerate the development of secure, robust DeFi applications by providing well-tested, extensible smart contract patterns. Source code is available at the official repository.

Why Use It

Building secure DeFi protocols from scratch requires deep domain expertise, familiarity with Solidity, and an understanding of common attack vectors and best practices. By leveraging production-ready templates, developers can:

  • Reduce Development Time: Skip boilerplate implementation and focus on application-specific business logic.
  • Enhance Security: Build upon patterns that implement established practices, including reentrancy guards, ownership controls, and safe token interactions.
  • Ensure Interoperability: Use templates compatible with major DeFi standards, making integration with wallets, aggregators, and analytics straightforward.
  • Accelerate Auditing: Start from a codebase familiar to auditors and the broader developer community, reducing the learning curve and risk of hidden bugs.

How to Use It

To use the DeFi Protocol Templates skill, install or import the relevant template contracts into your smart contract project. Each template is ready for customization and extension to fit your application's needs. Below are example usages for several included protocol types:

Staking Contract Example

The staking template provides a reward distribution mechanism, allowing users to stake ERC20 tokens and earn rewards in another ERC20 token. The template includes support for ownership restrictions, reentrancy protection, and customizable reward rates.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract StakingRewards is ReentrancyGuard, Ownable {
    IERC20 public stakingToken;
    IERC20 public rewardsToken;

    uint256 public rewardRate = 100; // Rewards per second
    uint256 public lastUpdateTime;
    uint256 public rewardPerTokenStored;

    mapping(address => uint256) public userRewardPerTokenPaid;
    mapping(address => uint256) public rewards;
    mapping(address => uint256) public balances;

    uint256 private _totalSupply;

    event Staked(address indexed user, uint256 amount);
    event Withdrawn(address indexed user, uint256 amount);
    event RewardPaid(address indexed user, uint256 reward);

    constructor(address _stakingToken, address _rewardsToken) {
        stakingToken = IERC20(_stakingToken);
        rewardsToken = IERC20(_rewardsToken);
    }

    // Stake tokens to earn rewards
    function stake(uint256 amount) external nonReentrant {
        require(amount > 0, "Cannot stake 0");
        _totalSupply += amount;
        balances[msg.sender] += amount;
        stakingToken.transferFrom(msg.sender, address(this), amount);
        emit Staked(msg.sender, amount);
    }

    // Withdraw tokens
    function withdraw(uint256 amount) external nonReentrant {
        require(amount > 0, "Cannot withdraw 0");
        _totalSupply -= amount;
        balances[msg.sender] -= amount;
        stakingToken.transfer(msg.sender, amount);
        emit Withdrawn(msg.sender, amount);
    }

    // Claim rewards
    function getReward() external nonReentrant {
        uint256 reward = rewards[msg.sender];
        if (reward > 0) {
            rewards[msg.sender] = 0;
            rewardsToken.transfer(msg.sender, reward);
            emit RewardPaid(msg.sender, reward);
        }
    }
}

Other Templates

  • AMM (Automated Market Maker): Supports liquidity pools, trading, and fee distribution, following the model of protocols like Uniswap.
  • Governance: Implements voting and proposal systems for on-chain decision making.
  • Lending/Borrowing: Provides mechanisms for depositing collateral, borrowing assets, and managing interest rates and liquidation.
  • Flash Loans: Enables atomic, uncollateralized loans to facilitate arbitrage and complex DeFi operations.

Each template comes with modular functions, event emission for tracking, and integration points for frontend or off-chain services.

When to Use It

Use the DeFi Protocol Templates skill in the following scenarios:

  • Building a Staking Platform: Launch a token staking system with reward distribution in minutes.
  • Implementing AMM Protocols: Create decentralized exchanges or liquidity pools with proven, extensible smart contract blueprints.
  • Creating On-chain Governance: Add voting and proposal features for token holders to manage protocol upgrades or treasury allocations.
  • Developing Lending/Borrowing Platforms: Introduce DeFi money market features, including collateral management and liquidations.
  • Integrating Flash Loans: Offer advanced DeFi functionality such as arbitrage, refinancing, or atomic multi-step operations.
  • Launching Yield Farming Systems: Combine staking, liquidity mining, and rewards for incentivizing user participation.

Important Notes

  • Security Review Required: While the templates use best practices, always conduct thorough audits and testing. Customize code responsibly to avoid introducing vulnerabilities.
  • Extensibility: Templates are designed for extension. Developers can override functions, add access controls, or integrate with oracles and other DeFi protocols.
  • Compliance: Ensure your application complies with local regulations, especially for lending and governance features.
  • Dependency Management: The templates rely on OpenZeppelin contracts for security and composability. Keep dependencies up to date to mitigate known vulnerabilities.
  • Gas Costs: DeFi protocols can be gas-intensive. Profile and optimize your application as needed, especially for high-frequency operations or when scaling to mainnet.

By leveraging DeFi Protocol Templates, developers can rapidly prototype, experiment, and launch secure, feature-rich DeFi applications, focusing on innovation and user experience instead of reinventing foundational components.