Variable
State Variable (状态变量):状态变量是在合约内声明的变量,其数据存储在区块链上。
contract Demo {
uint public count; // 声明状态变量 count
}
Local Variable (本地变量):本地变量是在函数内声明的变量,其数据存储在内存中。函数执行完后,内存会被释放。
contract Demo {
function calculateSum(uint a, uint b) public pure returns (uint) {
uint c = a + b;
return c;
}
// 上例的 a b c 都是本地变量
}
Global Variable (全局变量):全局变量是 Solidity 提供的特殊变量,用于获取区块链相关的信息。
-
区块属性
-
block.basefee
(uint):当前区块的基础费用 -
block.chainid
(uint):当前链的 ID -
block.difficulty
(uint):当前区块的难度 -
block.gaslimit
(uint):当前区块的 gas 限额 -
block.number
(uint):当前区块号 -
block.timestamp
(uint):当前区块的时间戳,为 unix 纪元以来的秒 -
block.coinbase
(address):当前区块的矿工地址 -
block.blobbasefee
(uint):当前区块的 blob 基础费用。这是 Cancun 升级新增的全局变量
-
-
交易属性
-
tx.gasprice
(uint):交易所需的 gas -
tx.origin
(address):交易发起者的地址
-
-
消息属性
-
msg.data
(bytes):调用数据 (calldata) -
msg.sig
(bytes4):调用数据的前 4 个字节 (即函数选择器) -
msg.value
(uint):随调用发送的以太币数量 (以 wei 为单位) -
msg.sender
(address):调用者的地址
-
-
工具函数
-
gasleft() returns (uint)
:返回剩余的 gas -
blockhash(uint blockNumber) returns (bytes32)
:返回指定区块的哈希值(仅适用于最近的 256 个区块,不包含当前区块) -
blobhash(uint index) returns (bytes32)
:返回跟当前交易关联的第 index 个 blob 的版本化哈希(第一个字节为版本号,当前为 0x01,后面接 KZG 承诺的 SHA256 哈希的最后 31 个字节)。若当前交易不包含 blob,则返回空字节。这是 Cancun 升级新增的全局变量。
-
contract Demo {
function getGlobalVariables() public view returns (address, uint) {
address sender = msg.sender; // 调用者的地址
uint timestamp = block.timestamp; // 当前区块的时间戳
return (sender, timestamp);
}
}
以太币的常用单位
wei、gwei、ether 是 ETH (以太币) 的常用单位。
- 1 ether = 10^18 wei;wei 是以太币的最小单位;这是 Solidity 中以太币的默认单位
uint public oneWei = 1 wei;
- 1 ether = 10^9 gwei;常用于表示交易费用 (gas price)
uint public oneGwei = 1 gwei;
- ether 是以太币的基本单位
uint public oneEther = 1 ether;
时间单位
Solidity 中的时间单位有 seconds、minutes、hours、days、weeks 。
contract Demo {
uint public oneSecond = 1; // 默认为秒
uint public oneMinute = 1 minutes; // 60 秒
uint public oneHour = 1 hours; // 3600 秒
uint public oneDay = 1 days; // 86400 秒
uint public oneWeek = 1 weeks; // 604800 秒
}