1. 单位

1.1. 常用单位

  • wei 是以太(Ether)的最小子单位(1 wei == 1)
  • gwei 是用于描述 gas 价格的常用子单位(1 gwei == 1e9)
  • ether 单位 (1 ether == 1e18)
注意:
在 Solidity 中,我们使用整数进行计算,且该语言不支持 浮点数 类型。浮点数表示问题会导致舍入错误(舍入),从而为攻击创造逻辑漏洞。

1.2. 时间单位

  • 1 == 1 秒
  • 1 分 == 60 秒
  • 1 小时 == 60 分
  • 1 天 == 24 小时
  • 1 周 == 7 天

示例

function f(uint start, uint daysAfter) public {
    if (block.timestamp >= start + daysAfter * 1 days) {
        // ...
    }
}

2. 全局变量

2.1. 区块和交易属性

  • blockhash(uint blockNumber) returns (bytes32): 给定区块的哈希值,当 区块号 属于最近 256 个区块之一;否则返回零
  • block.basefee (uint): 当前区块的基础费用
  • block.chainid (uint): 当前链 ID
  • block.coinbase (address payable): 当前区块打包矿工的地址
  • block.gaslimit (uint): 当前区块的 gas 限制
  • block.number (uint): 当前区块高度
  • block.timestamp (uint): 当前区块的时间戳(以自 Unix 纪元以来的秒数表示)
  • gasleft() returns (uint256): 剩余 gas
  • msg.data (bytes calldata): 完整的调用数据
  • msg.sender (address): 消息发送者(当前调用)
  • msg.sig (bytes4): 调用数据的前四个字节(即函数标识符)
  • msg.value (uint): 随消息发送的 wei 数量
  • tx.gasprice (uint): 交易的 gas 价格
  • tx.origin(地址): 交易的发送方(完整的调用链)

2.2. 错误处理

  • assert(bool condition): 如果条件不满足,则引发 Panic 错误并回滚状态更改——用于内部错误。
  • require(bool condition): 如果条件不满足则回滚——用于输入或外部组件中的错误。
  • require(bool condition, string memory message): 如果条件不满足则回滚——用于输入或外部组件中的错误,同时提供错误信息。
  • revert(): 中止执行并回滚状态更改
  • revert(string memory reason): 中止执行并回滚状态更改,提供解释性字符串

2.3. 地址类型成员

  • <address>.balance (uint256): 地址的 Wei 余额
  • <address>.code (bytes memory): 该地址的代码(可以为空)
  • <address>.codehash (bytes32): 该地址的 codehash
  • <address payable>.transfer(uint256 amount): 向地址发送指定数量的 Wei,失败时回滚,转发 2300 gas 补贴,不可调节
  • <address payable>.send(uint256 amount) returns (bool): 向地址发送指定数量的 Wei,失败时返回 false,转发 2300 gas 补贴,不可调节
  • <address>.call(bytes memory) returns (bool, bytes memory): 使用给定的有效负载发出底层 CALL,返回成功状态和返回数据,转发所有可用 gas,可调节
  • <address>.delegatecall(bytes memory) returns (bool, bytes memory): 使用给定的有效负载发出底层 DELEGATECALL,返回成功状态和返回数据,转发所有可用 gas,可调节
  • <address>.staticcall(bytes memory) returns (bool, bytes memory): 使用给定的有效负载发出底层 STATICCALL,返回成功状态和返回数据,转发所有可用 gas,可调节

2.4. 合约相关关键字

  • this:当前合约,可显式转换为 Address
  • super:继承层次结构中高一级的合约
  • selfdestruct(address payable recipient):销毁当前合约,将其资金发送至指定地址并终止执行。请注意,selfdestruct 具有继承自 EVM 的一些特殊性质:
    • 接收合约的 receive 函数不会执行。
    • 合约仅在交易结束时才真正被销毁,回滚(revert)可能会“撤销”销毁操作。

‍

3. 表达式与控制结构

3.1. 支持的关键字

存在: if, else, while, do, 资本, break, continue, 返回, try/catch 具有 C 或 JavaScript 中常见的语义。

3.2. 函数调用

我们可以调用 函数 中的 1 合约 来自另一个 合约。下面是一个包含 2 个合约的示例 调用方 以及 被调用方.

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

contract Callee {
    uint public x;
    uint public value;

    function setX(uint _x) public returns (uint) {
        x = _x;
        return x;
    }

    function setXandSendEther(uint _x) public payable returns (uint, uint) {
        x = _x;
        value = msg.value;

        return (x, value);
    }
}

contract Caller {
    function setX(Callee _callee, uint _x) public {
        uint x = _callee.setX(_x);
    }

    function setXFromAddress(address _addr, uint _x) public {
        Callee callee = Callee(_addr);
        callee.setX(_x);
    }

    function setXandSendEther(Callee _callee, uint _x) public payable {
        (uint x, uint value) = _callee.setXandSendEther{value: msg.value}(_x);
    }
}

3.3. 使用关键字创建新合约 new

我们可以使用关键字 new 来创建一个新合约。 AdvancedStorage.sol 示例将对此进行更详细的解释。

4. 高级存储

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

contract AdvancedStorage {
    // Declare the address of a vault manager
    address public vaultManager;

    // Declare an error type for unauthorized access
    error OwnableUnauthorizedAccount(address account);

    // Constructor is a function that runs when the contract is initialized
    constructor() {
        // Assign the address of the deployer to the vault manager variable
        vaultManager = msg.sender;
    }

    // Declare the InvestmentVault Struct data type
    struct InvestmentVault {
        uint256 investmentDuration; // Thời gian đầu tư
        int256 returnOnInvestment; // % lãi suất trả về
        bool initialized; // Đã khởi tạo
        address identityCard; // Địa chỉ thẻ thông tin
    }
    // Declare a variable with the InvestmentVault type
    InvestmentVault private investmentVault;

    // This function initializes the investment vault
    function setInitialInvestmentVault(uint256 daysAfter, int256 _returnOnInvestment, address _vaultOwner) public {
        // We check if the initiator is the vaultManager
        if (msg.sender != vaultManager) {
            // This reverts all actions and reverts the transaction
            revert OwnableUnauthorizedAccount(msg.sender);
        }
        // Declare the investment duration
        uint256 _investmentDuration = block.timestamp + daysAfter * 1 days;

        // Create a new identity card for the customer
        CustomerIdentityCard customerIdentityCard = new CustomerIdentityCard(_vaultOwner);
        // Assign the address of the vault owner/customer to the mapping with the vault information
        investmentVault = InvestmentVault({investmentDuration: _investmentDuration, returnOnInvestment: _returnOnInvestment, initialized: true, identityCard: address(customerIdentityCard)});
    }

    // Function to change the return on investment
    function editReturnOnInvestment(int256 _newReturnOnInvestment) public {
        // require keyword works similarly to if and revert above
        require (msg.sender == vaultManager, "Unauthorized Manager");
        // Change the value of the interest rate
        investmentVault.returnOnInvestment = _newReturnOnInvestment;
    }

    // Function to return investmentVault information
    function retrieveInvestmentVault() public view returns (InvestmentVault memory _investmentVault) {
        return investmentVault;
    }

    // Function to return the address of the IdentityCard
    function retrieveCustomerInformation() public view returns (address) {
        return CustomerIdentityCard(investmentVault.identityCard).customer();
    }
}

// Contract that stores the address of the vault owner
contract CustomerIdentityCard {
    //  declares a variable to store the address of the customer
    address public customer;

    // initialize the contract and assign the address of the customer
    constructor(address _customer) {
        customer = _customer;
    }
}