如何在 Linea 上编写和部署简单的稳定币

了解如何在 Linea 网络上编写和部署您自己的稳定币

6 分钟阅读
如何在 Linea 上编写和部署简单的稳定币

稳定币已成为区块链和 Web3 生态系统的重要组成部分,帮助用户规避比特币和以太坊等加密货币的价格波动。在本文中,我们将了解稳定币的概念,以及如何在 Linea 上编写并部署一个简单的稳定币合约。

什么是稳定币?

稳定币是一种旨在保持价值稳定的加密货币。其实现方式是将自身价值与更稳定的资产挂钩,例如美元等法定货币、黄金等大宗商品,甚至其他加密货币。稳定币的目标是将加密货币的优势(如快速交易和去中心化)与传统金融资产的稳定性相结合,使其在日常交易中更加可靠、实用。

稳定币可根据多种因素进行分类,包括抵押结构、稳定机制和相对稳定性。以下是稳定币类型的全面解析:

1. 法币抵押稳定币

法币抵押稳定币由美元或欧元等传统货币作为储备支撑,例如 Tether USDT 和 USD Coin USDC。由于与法币直接挂钩,此类稳定币稳定性强、易于使用。但它们依赖中心化机构管理储备,并面临监管审查。

2. 加密资产抵押稳定币

加密资产抵押稳定币(如 DAI 和 LUSD)以其他加密货币作为抵押,通常采用超额抵押机制以应对加密市场的波动性。与法币支持的稳定币相比,此类稳定币去中心化程度更高。但其机制较为复杂,在市场下行期间稳定性可能较差,需要主动管理以维持稳定。

3. 算法稳定币

算法稳定币(如 Ampleforth (AMPL))依靠算法调节供应量并稳定价格,无需直接抵押。此类稳定币去中心化程度高、灵活性强,但机制难以理解,且一旦市场信心下滑,可能面临价值迅速崩溃的风险(即"死亡螺旋")。

此外还有其他几种类型:混合稳定币(如 Frax (FRAX))结合了抵押和算法机制来实现稳定,在不同模型之间取得平衡,但复杂度较高;大宗商品支持稳定币(如 Paxos Gold (PAXG))与实物资产挂钩,为用户提供接触现实世界大宗商品的数字化途径;收益型稳定币(如 Compound USD (cUSDC))通过借贷或投资产生收益,提供被动收入,但伴随较高的相关风险。

了解了稳定币的概念及当前生态系统中的稳定币类型后,让我们来探索如何在 Linea 网络上创建稳定币。

搭建开发环境

第一步是确保您的开发环境已正确配置:

  • 安装 Node.js 和 npm(Node 包管理器)。

  • 运行以下命令安装 Hardhat:

npm install --save-dev hardhat

创建新的 Hardhat 项目

在您的项目目录中,初始化一个新的 Hardhat 项目:

npx hardhat init

本教程将使用 TypeScript,Hardhat 已为您准备好所有必要的依赖项。初始化完成后,您将获得如下项目结构:

  • contracts/:Solidity 合约

  • ignition/:Ignition 部署模块

  • test/:测试文件

  • hardhat.config.js:Hardhat 配置文件

现在,让我们开始编写我们自己的稳定币合约 RadStablecoin (RAD)。这将是一个简单的以太坊抵押稳定币,抵押率为 150%。

在本合约中:

  • ETH 将用作抵押品。

  • 150% 抵押率将确保稳定性。

  • 用户可通过发送 ETH 来铸造稳定币,也可通过销毁稳定币来取回抵押品。

  • 将使用简单的价格预言机获取 ETH 价格(在实际场景中,您应使用安全的去中心化预言机)。

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

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

/// @title RadStablecoin
/// @notice A simple stablecoin implementation with collateral-based minting
/// @dev Inherits from ERC20 and Ownable
contract RadStablecoin is ERC20, Ownable {
    /// @notice The collateralization ratio (150%)
    uint256 public constant COLLATERAL_RATIO = 150;

    /// @notice The precision for price calculations (2 decimal places)
    uint256 public constant PRICE_PRECISION = 100;

    /// @notice Mapping to track collateral balances for each user
    mapping(address => uint256) public collateralBalances;

    /// @notice Initializes the RadStablecoin contract
    constructor() ERC20("RadStablecoin", "RAD") {}

    /// @notice Allows users to deposit LineaETH as collateral
    /// @dev The deposited amount is added to the user's collateral balance
    function depositCollateral() external payable {
        collateralBalances[msg.sender] += msg.value;
    }

    /// @notice Allows users to withdraw their deposited collateral
    /// @dev Implements the checks-effects-interactions pattern to prevent reentrancy
    /// @param amount The amount of collateral to withdraw (in wei)
    function withdrawCollateral(uint256 amount) external {
        require(collateralBalances[msg.sender] >= amount, "Insufficient collateral");
        collateralBalances[msg.sender] -= amount; // Update state before making external call
        payable(msg.sender).transfer(amount);     // Safely transfer LineaETH after updating state
    }

    /// @notice Mints stablecoin (RAD) based on the user's deposited collateral
    /// @dev Calculates required collateral based on current LineaETH price and mints RAD tokens
    /// @param stablecoinAmount The amount of stablecoin to mint
    function mintStablecoin(uint256 stablecoinAmount) external {
        uint256 collateralRequired = (stablecoinAmount * COLLATERAL_RATIO * PRICE_PRECISION) / (100 * getCurrentPrice());
        require(collateralBalances[msg.sender] >= collateralRequired, "Insufficient collateral");

        collateralBalances[msg.sender] -= collateralRequired;
        _mint(msg.sender, stablecoinAmount);
    }

    /// @notice Burns stablecoin (RAD) and returns the equivalent collateral to the user
    /// @dev Calculates collateral to return based on current LineaETH price and burns RAD tokens
    /// @param stablecoinAmount The amount of stablecoin to burn
    function burnStablecoin(uint256 stablecoinAmount) external {
        require(balanceOf(msg.sender) >= stablecoinAmount, "Insufficient stablecoin balance");

        uint256 collateralToReturn = (stablecoinAmount * COLLATERAL_RATIO * PRICE_PRECISION) / (100 * getCurrentPrice());
        _burn(msg.sender, stablecoinAmount);
        collateralBalances[msg.sender] += collateralToReturn;
    }

    /// @notice Gets the current price of LineaETH in USD
    /// @dev In a real-world scenario, this would fetch the price from an oracle
    /// @return The current LineaETH price in USD (fixed at $2000 for simplicity)
    function getCurrentPrice() public view returns (uint256) {
        // In a real-world scenario, this would fetch the current LineaETH/USD price from an oracle
        // For simplicity, we'll use a fixed price of $2000 per LineaETH
        return 200000; // $2000.00
    }
}
复制
  1. 抵押品管理:- 存入抵押品:- 用户可通过调用 depositCollateral 将 以太币(ETH) 作为抵押品存入。

  • 存入的 ETH 记录在 collateralBalances 映射中,用于追踪用户的总抵押量。

  • 提取抵押品:- 用户可使用 withdrawCollateral 提取其抵押品。

  1. 稳定币操作:- 铸造稳定币:- mintStablecoin 函数确保用户拥有足够的抵押品,以铸造所请求数量的 RAD 代币。

  • 销毁稳定币:- burnStablecoin 函数销毁指定数量的 RAD,并根据 150% 抵押率和 ETH 当前价格返还等值的 ETH。

  1. 价格数据:- 获取 ETH 价格:- 合约包含 getCurrentPrice 函数,在本简化示例中返回 ETH 的固定价格 $2000。

为 Linea 配置 Hardhat

更新您的 hardhat.config.js,加入 Linea 测试网配置。添加以下网络配置:

import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import * as dotenv from "dotenv";

dotenv.config();

const config: HardhatUserConfig = {
  solidity: "0.8.24",
  networks: {
    "linea-testnet": {
      url: `https://linea-sepolia.infura.io/v3/${process.env.INFURA_API_KEY}`,
      accounts: [process.env.ACCOUNT_PRIVATE_KEY!],
    },
  },
};
export default config;
复制

创建部署脚本

在 ignition/modules/ 目录中,创建名为 RadStablecoin.ts 的文件,并添加以下脚本:

import { buildModule } from "@nomicfoundation/hardhat-ignition/modules";

const RadStablecoinModule = buildModule("RadStablecoinModule", (m) => {
  // Deploy the RadStablecoin contract
  const radStablecoin = m.contract("RadStablecoin");

  // Return the deployed contract instance
  return { radStablecoin };
});

export default RadStablecoinModule;
复制

运行以下命令编译合约:

npx hardhat compile

在部署智能合约之前,请确保在目录中的 .env 文件中更新以下值:

# Infura API key for connecting to Ethereum networks
INFURA_API_KEY=your_infura_api_key_here

# Private key of the account to be used for deployments and transactions
ACCOUNT_PRIVATE_KEY=your_account_private_key_here
复制

部署合约

最后,将 RadStablecoin 合约部署到 Linea:

npx hardhat ignition deploy ignition/modules/RadStablecoin.ts --network linea-testnet

这将在 Linea Sepolia 上部署该市场智能合约。

下一步?

稳定币在加密货币生态系统中发挥着至关重要的作用,为金融应用提供了急需的稳定性。在本教程中,我们探讨了稳定币的核心概念、各种类型,以及它们如何将传统金融与去中心化技术相连接。我们还通过在 Linea 网络上创建并部署 RadStablecoin,积累了实践经验,深化了对抵押支持稳定币的理解——祝编码愉快!

AI 翻译。可能包含错误。请务必核实信息。

评价此翻译