К основному содержанию
скилл CX Codex

defi-protocol-templates · ormus-solutions — скилл для Claude Code: DeFi-шаблоны

defi-protocol-templates — скилл для Claude Code с шаблонами смарт-контрактов DeFi. Он подключается при разработке протоколов стейкинга, обмена токенов и кредитования.

MIT ★ 126 обновлён 2026-10-04

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add Ormus-Solutions/LibreUIUX-Claude-Code
/plugin install blockchain-web3@libreuiux
Открыть на GitHub

Что делает defi-protocol-templates

Скилл даёт шаблоны для DeFi-протоколов: стейкинга с распределением наград, автоматизированного маркетмейкера (AMM), управления токенами, кредитования и флеш-кредитов. В описании также названы платформы для фарминга доходности.

В примерах контрактов используется Solidity с прагмой ^0.8.0 и импортами @openzeppelin/contracts. Код показывает логику стейкинга и AMM: добавление и снятие ликвидности, обмен токенов и начисление наград. Для сборки контрактов из примеров нужны Solidity и контракты OpenZeppelin.

Какие задачи решает

  • создать контракт стейкинга с распределением наград
  • добавить в протокол обмен токенов через AMM
  • подготовить систему управления токенами
  • спроектировать контракт кредитования или флеш-кредита

Примеры запросов агенту

  • Создай контракт стейкинга с распределением наград для моего DeFi-протокола.
  • Добавь в проект AMM с обменом токенов и управлением ликвидностью.
  • Подготовь шаблон протокола кредитования на Solidity.

Как установить defi-protocol-templates

1Через маркетплейс плагинов

/plugin marketplace add Ormus-Solutions/LibreUIUX-Claude-Code
/plugin install blockchain-web3@libreuiux

Команда ставит плагин blockchain-web3 целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add Ormus-Solutions/LibreUIUX-Claude-Code --skill defi-protocol-templates -a claude-code

3Вручную: положить файлы

~/.claude/skills/defi-protocol-templates/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/defi-protocol-templates/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о defi-protocol-templates

Как установить defi-protocol-templates в Claude Code?

Добавь маркетплейс командой /plugin marketplace add Ormus-Solutions/LibreUIUX-Claude-Code, затем установи плагин командой /plugin install blockchain-web3@libreuiux.

Что делает defi-protocol-templates?

Даёт шаблоны для стейкинга, AMM, управления токенами, кредитования и флеш-кредитов. В примерах показаны контракты Solidity для стейкинга и обмена токенов.

Что нужно для работы defi-protocol-templates?

В примерах контрактов используются Solidity с прагмой ^0.8.0 и импорты @openzeppelin/contracts.

Исходный текст

SKILL.md · MIT
---
name: defi-protocol-templates
description: Implement DeFi protocols with production-ready templates for staking, AMMs, governance, and lending systems. Use when building decentralized finance applications or smart contract protocols.
---

# DeFi Protocol Templates

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

## When to Use This Skill

- Building staking platforms with reward distribution
- Implementing AMM (Automated Market Maker) protocols
- Creating governance token systems
- Developing lending/borrowing protocols
- Integrating flash loan functionality
- Launching yield farming platforms

## Staking Contract

```solidity
// 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);
    }

    modifier updateReward(address account) {
        rewardPerTokenStored = rewardPerToken();
        lastUpdateTime = block.timestamp;

        if (account != address(0)) {
            rewards[account] = earned(account);
            userRewardPerTokenPaid[account] = rewardPerTokenStored;
        }
        _;
    }

    function rewardPerToken() public view returns (uint256) {
        if (_totalSupply == 0) {
            return rewardPerTokenStored;
        }
        return rewardPerTokenStored +
            ((block.timestamp - lastUpdateTime) * rewardRate * 1e18) / _totalSupply;
    }

    function earned(address account) public view returns (uint256) {
        return (balances[account] *
            (rewardPerToken() - userRewardPerTokenPaid[account])) / 1e18 +
            rewards[account];
    }

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

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

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

    function exit() external {
        withdraw(balances[msg.sender]);
        getReward();
    }
}
```

## AMM (Automated Market Maker)

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract SimpleAMM {
    IERC20 public token0;
    IERC20 public token1;

    uint256 public reserve0;
    uint256 public reserve1;

    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;

    event Mint(address indexed to, uint256 amount);
    event Burn(address indexed from, uint256 amount);
    event Swap(address indexed trader, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out);

    constructor(address _token0, address _token1) {
        token0 = IERC20(_token0);
        token1 = IERC20(_token1);
    }

    function addLiquidity(uint256 amount0, uint256 amount1) external returns (uint256 shares) {
        token0.transferFrom(msg.sender, address(this), amount0);
        token1.transferFrom(msg.sender, address(this), amount1);

        if (totalSupply == 0) {
            shares = sqrt(amount0 * amount1);
        } else {
            shares = min(
                (amount0 * totalSupply) / reserve0,
                (amount1 * totalSupply) / reserve1
            );
        }

        require(shares > 0, "Shares = 0");
        _mint(msg.sender, shares);
        _update(
            token0.balanceOf(address(this)),
            token1.balanceOf(address(this))
        );

        emit Mint(msg.sender, shares);
    }

    function removeLiquidity(uint256 shares) external returns (uint256 amount0, uint256 amount1) {
        uint256 bal0 = token0.balanceOf(address(this));
        uint256 bal1 = token1.balanceOf(address(this));

        amount0 = (shares * bal0) / totalSupply;
        amount1 = (shares * bal1) / totalSupply;

        require(amount0 > 0 && amount1 > 0, "Amount0 or amount1 = 0");

        _burn(msg.sender, shares);
        _update(bal0 - amount0, bal1 - amount1);

        token0.transfer(msg.sender, amount0);
        token1.transfer(msg.sender, amount1);

        emit Burn(msg.sender, shares);
    }

    function swap(address tokenIn, uint256 amountIn) external returns (uint256 amountOut) {
        require(tokenIn == address(token0) || tokenIn == address(token1), "Invalid token");

        bool isToken0 = tokenIn == address(token0);
        (IERC20 tokenIn_, IERC20 tokenOut, uint256 resIn, uint256 resOut) = isToken0
            ? (token0, token1, reserve0, reserve1)
            : (token1, token0, reserve1, reserve0);

        tokenIn_.transferFrom(msg.sender, address(this), amountIn);

        // 0.3% fee
        uint256 amountInWithFee = (amountIn * 997) / 1000;
        amountOut = (resOut * amountInWithFee) / (resIn + amountInWithFee);

        tokenOut.transfer(msg.sender, amountOut);

        _update(
            token0.balanceOf(address(this)),
            token1.balanceOf(address(this))
        );

        emit Swap(msg.sender, isToken0 ? amountIn : 0, isToken0 ? 0 : amountIn, isToken0 ? 0 : amountOut, isToken0 ? amountOut : 0);
    }

    function _mint(address to, uint256 amount) private {
        balanceOf[to] += amount;
        totalSupply += amount;
    }

    function _burn(address from, uint256 amount) private {
        balanceOf[from] -= amount;
        totalSupply -= amount;
    }

    function _update(uint256 res0, uint256 res1) private {
        reserve0 = res0;
        reserve1 = res1;
    }

    function sqrt(uint256 y) private pure returns (uint256 z) {
        if (y > 3) {
            z = y;
            uint256 x = y / 2 + 1;
            while (x < z) {
                z = x;
                x = (y / x + x) / 2;
            }
        } else if (y != 0) {
            z = 1;
        }
    }

    function min(uint256 x, uint256 y) private pure returns (uint256) {
        return x <= y ? x : y;
    }
}
```

## Governance Token

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

import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract GovernanceToken is ERC20Votes, Ownable {
    constructor() ERC20("Governance Token", "GOV") ERC20Permit("Governance Token") {
        _mint(msg.sender, 1000000 * 10**decimals());
    }

    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal override(ERC20Votes) {
        super._afterTokenTransfer(from, to, amount);
    }

    function _mint(address to, uint256 amount) internal override(ERC20Votes) {
        super._mint(to, amount);
    }

    function _burn(address account, uint256 amount) internal override(ERC20Votes) {
        super._burn(account, amount);
    }
}

contract Governor is Ownable {
    GovernanceToken public governanceToken;

    struct Proposal {
        uint256 id;
        address proposer;
        string description;
        uint256 forVotes;
        uint256 againstVotes;
        uint256 startBlock;
        uint256 endBlock;
        bool executed;
        mapping(address => bool) hasVoted;
    }

    uint256 public proposalCount;
    mapping(uint256 => Proposal) public proposals;

    uint256 public votingPeriod = 17280; // ~3 days in blocks
    uint256 public proposalThreshold = 100000 * 10**18;

    event ProposalCreated(uint256 indexed proposalId, address proposer, string description);
    event VoteCast(address indexed voter, uint256 indexed proposalId, bool support, uint256 weight);
    event ProposalExecuted(uint256 indexed proposalId);

    constructor(address _governanceToken) {
        governanceToken = GovernanceToken(_governanceToken);
    }

    function propose(string memory description) external returns (uint256) {
        require(
            governanceToken.getPastVotes(msg.sender, block.number - 1) >= proposalThreshold,
            "Proposer votes below threshold"
        );

        proposalCount++;
        Proposal storage newProposal = proposals[proposalCount];
        newProposal.id = proposalCount;
        newProposal.proposer = msg.sender;
        newProposal.description = description;
        newProposal.startBlock = block.number;
        newProposal.endBlock = block.number + votingPeriod;

        emit ProposalCreated(proposalCount, msg.sender, description);
        return proposalCount;
    }

    function vote(uint256 proposalId, bool support) external {
        Proposal storage proposal = proposals[proposalId];
        require(block.number >= proposal.startBlock, "Voting not started");
        require(block.number <= proposal.endBlock, "Voting ended");
        require(!proposal.hasVoted[msg.sender], "Already voted");

        uint256 weight = governanceToken.getPastVotes(msg.sender, proposal.startBlock);
        require(weight > 0, "No voting power");

        proposal.hasVoted[msg.sender] = true;

        if (support) {
            proposal.forVotes += weight;
        } else {
            proposal.againstVotes += weight;
        }

        emit VoteCast(msg.sender, proposalId, support, weight);
    }

    function execute(uint256 proposalId) external {
        Proposal storage proposal = proposals[proposalId];
        require(block.number > proposal.endBlock, "Voting not ended");
        require(!proposal.executed, "Already executed");
        require(proposal.forVotes > proposal.againstVotes, "Proposal failed");

        proposal.executed = true;

        // Execute proposal logic here

        emit ProposalExecuted(proposalId);
    }
}
```

## Flash Loan

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IFlashLoanReceiver {
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 fee,
        bytes calldata params
    ) external returns (bool);
}

contract FlashLoanProvider {
    IERC20 public token;
    uint256 public feePercentage = 9; // 0.09% fee

    event FlashLoan(address indexed borrower, uint256 amount, uint256 fee);

    constructor(address _token) {
        token = IERC20(_token);
    }

    function flashLoan(
        address receiver,
        uint256 amount,
        bytes calldata params
    ) external {
        uint256 balanceBefore = token.balanceOf(address(this));
        require(balanceBefore >= amount, "Insufficient liquidity");

        uint256 fee = (amount * feePercentage) / 10000;

        // Send tokens to receiver
        token.transfer(receiver, amount);

        // Execute callback
        require(
            IFlashLoanReceiver(receiver).executeOperation(
                address(token),
                amount,
                fee,
                params
            ),
            "Flash loan failed"
        );

        // Verify repayment
        uint256 balanceAfter = token.balanceOf(address(this));
        require(balanceAfter >= balanceBefore + fee, "Flash loan not repaid");

        emit FlashLoan(receiver, amount, fee);
    }
}

// Example flash loan receiver
contract FlashLoanReceiver is IFlashLoanReceiver {
    function executeOperation(
        address asset,
        uint256 amount,
        uint256 fee,
        bytes calldata params
    ) external override returns (bool) {
        // Decode params and execute arbitrage, liquidation, etc.
        // ...

        // Approve repayment
        IERC20(asset).approve(msg.sender, amount + fee);

        return true;
    }
}
```

## Resources

- **references/staking.md**: Staking mechanics and reward distribution
- **references/liquidity-pools.md**: AMM mathematics and pricing
- **references/governance-tokens.md**: Governance and voting systems
- **references/lending-protocols.md**: Lending/borrowing implementation
- **references/flash-loans.md**: Flash loan security and use cases
- **assets/staking-contract.sol**: Production staking template
- **assets/amm-contract.sol**: Full AMM implementation
- **assets/governance-token.sol**: Governance system
- **assets/lending-protocol.sol**: Lending platform template

## Best Practices

1. **Use Established Libraries**: OpenZeppelin, Solmate
2. **Test Thoroughly**: Unit tests, integration tests, fuzzing
3. **Audit Before Launch**: Professional security audits
4. **Start Simple**: MVP first, add features incrementally
5. **Monitor**: Track contract health and user activity
6. **Upgradability**: Consider proxy patterns for upgrades
7. **Emergency Controls**: Pause mechanisms for critical issues

## Common DeFi Patterns

- **Time-Weighted Average Price (TWAP)**: Price oracle resistance
- **Liquidity Mining**: Incentivize liquidity provision
- **Vesting**: Lock tokens with gradual release
- **Multisig**: Require multiple signatures for critical operations
- **Timelocks**: Delay execution of governance decisions

© Seth Hobson · MIT · Ormus-Solutions/LibreUIUX-Claude-Code

Похожие скиллы

Все скиллы по теме «Бэкенд и API» →

Сначала — defi-protocol-templates от других авторов.

defi-protocol-templates Seth Hobson Скилл defi-protocol-templates даёт Solidity-шаблоны для стейкинга и AMM, а также систем управления и flash loan. Пригодится при создании DeFi-протокола. CX Codex +1 10 400установок emblem-defi-yield EmblemAI Скилл emblem-defi-yield для исследования доходности в DeFi, проверки позиций через Nansen и входа в ликвидный стейкинг свопами на Solana, Ethereum, Base, BSC, Polygon и Hedera. CX Codex +1 8 700установок DeFi Yield Finder — Best APY Across 100+ Protocols axel-belfort DeFi Yield Finder — Best APY Across 100+ Protocols — MCP-сервер для поиска и сравнения доходностей в DeFi по 100+ протоколам с учётом APY, TVL и рисков. CX Codex +1 3 729установок DeFi Intelligence Engine danteriva45 MCP-сервер DeFi Intelligence Engine анализирует доходность, риски и безопасность смарт-контрактов в DeFi. Помогает распределять капитал и отслеживать ставки без ручного разбора пулов. CX Codex +1 1 348установок analyzing-ethereum-smart-contract-vulnerabilities mahipal Скилл analyzing-ethereum-smart-contract-vulnerabilities запускает статический и символьный анализ смарт-контрактов на Solidity через Slither и Mythril. Помогает находить reentrancy и ошибки переполнения до деплоя в сеть Ethereum. CX Codex +1 398установок Ethereum Developer ameya-2003 Промпт Ethereum Developer для ChatGPT и Claude.ai, который настраивает агента на роль Ethereum-разработчика. Задача — написать смарт-контракт на Solidity для блокчейн-мессенджера с публичным чтением и приватной записью. GP ChatGPT ★ 178 201звёзд репо ethskills austintgriffith Скилл ethskills для Claude Code, Codex, Cursor и других агентов, который даёт актуальный контекст по Ethereum, EVM и L2-сетям. Подключается при любой задаче со смарт-контрактами, DeFi-протоколами или деплоем dApp. CX Codex +1 2 500установок

Из того же набора42

Весь набор →
modern-form Промпт modern-form задаёт Claude Code структуру современных форм на Tailwind: поля, состояния валидации, доступность и типовые сценарии. GP ChatGPT ★ 126звёзд репо design-movements Скилл design-movements для Claude Code связывает направления дизайна от Arts and Crafts до Баухауса и швейцарского стиля с UI-токенами для интерфейсов. CX Codex +1 ★ 126звёзд репо premium-saas-design Скилл premium-saas-design для Claude Code проектирует премиум-сайты SaaS по циклу Define, Build, Review, Refine и семи артефактам контекста. Фиксирует дизайн-решения до кода при планировании посадки. CX Codex +1 ★ 126звёзд репо archetypal-combinations Скилл archetypal-combinations объединяет юнгианские архетипы и карты Старших арканов в единую дизайн-систему с палитрами и Tailwind-разметкой. CX Codex +1 ★ 126звёзд репо prompt-engineering-ui Скилл prompt-engineering-ui для Claude Code задаёт шаблоны промптов для генерации интерфейсов. Помогает точно передать дизайн-токены, состояния компонентов и требования доступности. CX Codex +1 ★ 126звёзд репо rapid-prototyping Скилл rapid-prototyping для быстрого создания одноразовых прототипов интерфейсов. Учит различать режим «вайб-кодинга» — когда скорость важнее качества — и режим ремесла, когда нужна надёжность. CX Codex +1 ★ 126звёзд репо synthesis-master Субагент synthesis-master координирует UI- и UX-плагины LibreUIUX в Claude Code. Применяет принципы дизайна, доступности, безопасности и скорости перед выпуском интерфейса в прод. CX Codex ★ 126звёзд репо ui-synth Команда ui-synth собирает запрос на интерфейс в план дизайна и реализации: от визуальной системы до тестов и SEO. Используйте её, когда хотите описать компонент или функцию и получить согласованный UI/UX. CX Codex +1 ★ 126звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой