- Solidity 教程
- Solidity - 首頁
- Solidity - 概覽
- Solidity - 環境搭建
- Solidity - 基本語法
- Solidity - 第一個應用
- Solidity - 註釋
- Solidity - 資料型別
- Solidity - 變數
- Solidity - 變數作用域
- Solidity - 運算子
- Solidity - 迴圈
- Solidity - 決策
- Solidity - 字串
- Solidity - 陣列
- Solidity - 列舉
- Solidity - 結構體
- Solidity - 對映
- Solidity - 型別轉換
- Solidity - 以太坊單位
- Solidity - 特殊變數
- Solidity - 樣式指南
- Solidity 函式
- Solidity - 函式
- Solidity - 函式修飾符
- Solidity - View 函式
- Solidity - Pure 函式
- Solidity - 回退函式
- 函式過載
- 數學函式
- 加密函式
- Solidity 常用模式
- Solidity - 提款模式
- Solidity - 訪問限制
- Solidity 高階
- Solidity - 合約
- Solidity - 繼承
- Solidity - 建構函式
- Solidity - 抽象合約
- Solidity - 介面
- Solidity - 庫
- Solidity - 彙編
- Solidity - 事件
- Solidity - 錯誤處理
- Solidity 有用資源
- Solidity - 快速指南
- Solidity - 有用資源
- Solidity - 討論
Solidity - 訪問限制
限制合約的訪問許可權是一種常見做法。預設情況下,合約狀態是隻讀的,除非它被指定為 public。
我們可以使用修飾符來限制誰可以修改合約的狀態或呼叫合約的函式。我們將建立並使用多個修飾符,如下所述:
onlyBy - 一旦用在某個函式上,則只有指定的呼叫者才能呼叫此函式。
onlyAfter - 一旦用在某個函式上,則該函式只能在特定時間段後呼叫。
costs - 一旦用在某個函式上,則只有在提供特定值的情況下,呼叫者才能呼叫此函式。
示例
pragma solidity ^0.5.0;
contract Test {
address public owner = msg.sender;
uint public creationTime = now;
modifier onlyBy(address _account) {
require(
msg.sender == _account,
"Sender not authorized."
);
_;
}
function changeOwner(address _newOwner) public onlyBy(owner) {
owner = _newOwner;
}
modifier onlyAfter(uint _time) {
require(
now >= _time,
"Function called too early."
);
_;
}
function disown() public onlyBy(owner) onlyAfter(creationTime + 6 weeks) {
delete owner;
}
modifier costs(uint _amount) {
require(
msg.value >= _amount,
"Not enough Ether provided."
);
_;
if (msg.value > _amount)
msg.sender.transfer(msg.value - _amount);
}
function forceOwnerChange(address _newOwner) public payable costs(200 ether) {
owner = _newOwner;
if (uint(owner) & 0 == 1) return;
}
}
廣告