基本定义本节是我们合约的开头,我们首先来介绍下合约的文件结构。一个单个合约文件的结构需要清晰、有条理,便于阅读、理解和维护。文件头部声明SPDX-License标识符用于声明合约的许可证类型(MIT、Apache-2.0等)。
本节是我们合约的开头,我们首先来介绍下合约的文件结构。一个单个合约文件的结构需要清晰、有条理,便于阅读、理解和维护。
// SPDX-License-Identifier: <license-name>。示例:
// SPDX-License-Identifier: MIT
^ 或 >= <,避免版本不兼容问题。示例:
pragma solidity ^0.8.0;
随着 solidity 编译器版本的升级,一些较早时间写的合约使用新版本的编译器编译会出现报错的情况,因此,合约头部声明需要指定版本范围。
import 语句导入其他合约、库或接口。<!---->
./。@openzeppelin/contracts/...。示例:
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./libraries/SafeMath.sol";
import "./interfaces/IUniswapV2Router.sol";
在文件中声明主要合约,以下是常见的内容组织方式:
address public owner。uint256 private _balance。constant 或 immutable 声明。mapping 或 struct。示例:
contract MyContract {
    address public owner; // 合约的管理员
    uint256 public totalSupply; // 总供应量
    mapping(address => uint256) private balances; // 用户余额
    uint256 public constant FEE_RATE = 2; // 手续费率
    bytes32 public immutable DOMAIN_SEPARATOR; // EIP-712 域分隔符
}
indexed 关键字支持事件过滤。示例:
event Transfer(address indexed from, address indexed to, uint256 amount);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
owner)。示例:
constructor(uint256 _initialSupply) {
    owner = msg.sender; // 部署者为管理员
    totalSupply = _initialSupply;
}
modifier 定义,_ 表示修饰符内插入函数代码。示例:
modifier onlyOwner() {
    require(msg.sender == owner, "Caller is not the owner");
    _;
}
modifier validAddress(address _addr) {
    require(_addr != address(0), "Invalid address");
    _;
}
函数分为以下几类,按顺序排列更清晰:
external 或 public ) :internal 或 private ) :view 或 pure ) :payable ) :ETH。fallback 和 receive ) :ETH 的情况。示例:
function transfer(address to, uint256 amount) external onlyOwner {
    require(to != address(0), "Invalid address");
    require(amount <= totalSupply, "Insufficient balance");
    totalSupply -= amount;
    balances[to] += amount;
    emit Transfer(msg.sender, to, amount);
}
function balanceOf(address account) external view returns (uint256) {
    return balances[account];
}
fallback() external payable {
    // 回退函数逻辑
}
示例:
function _safeTransfer(address to, uint256 amount) internal {
    require(to != address(0), "Invalid address");
    balances[to] += amount;
}
确保文件末尾有明确结束:
示例:
// End of MyContract                        如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!