Chúng ta sẽ xây dựng stablecoin cho Ethereum sử dụng Solidity và Foundry.

Trước tiên, ta sẽ cần định nghĩa các tính chất của nó:

  • Anchored: giá trị của nó sẽ được neo vào USD.
  • Algorithmic: sử dụng thuật toán để duy trì tính ổn định.
  • Exogenous: sử dụng tài sản thế chấp từ bên ngoài mà cụ thể là wrapped BTC và wrapped ETH.
import {ERC20Burnable, ERC20} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
 
// This is considered an Exogenous, Decentralized, Anchored (pegged), Crypto Collateralized low volatility coin
/*
 * @title: DecentralizedStableCoin
 * @author: Patrick "Long Course" Collins
 * Collateral: Exogenous (ETH & BTC)
 * Minting: Algorithmic
 * Relative Stability: Pegged to USD
 *
 * This is the contract meant to be governed by DSCEngine. This contract is just the ERC20 implementation of our stablecoin system.
 */
contract DecentralizedStableCoin is ERC20Burnable, Ownable {
    constructor(
        address initialOwner
    ) ERC20("DecentralizedStableCoin", "DSC") Ownable(initialOwner) {}
}

Về bản chất, stablecoin cũng là một ERC20 token mà có thêm hàm burn nên ta sẽ dùng extension ERC20Burnable của OpenZeppelin. Chúng ta sẽ cần phải triển khai 2 hàm quan trọng nhất là burnmint.

function burn(uint256 _amount) public override onlyOwner {
	uint256 balance = balanceOf(msg.sender);
	if (_amount <= 0) {
		revert DecentralizedStableCoin__MustBeMoreThanZero();
	}
	if (balance < _amount) {
		revert DecentralizedStableCoin__BurnAmountExceedsBalance();
	}
	super.burn(_amount);
}
function mint(
	address _to,
	uint256 _amount
) external onlyOwner returns (bool) {
	if (_to == address(0)) {
		revert DecentralizedStableCoin__NotZeroAddress();
	}
	if (_amount <= 0) {
		revert DecentralizedStableCoin__MustBeMoreThanZero();
	}
	_mint(_to, _amount);
	return true;
}

Resources