問題一覧に戻る
上級高度なパターン
問題92: ステートマシン
Solidityのステートマシンパターンを学習 - enumと修飾子で制御された状態遷移管理。ステートマシンは有効な状態遷移でビジネスロジックを強制し、無効な操作を防止。enumが可能な状態を定義し、修飾子が関数実行を保護。このパターンはワークフロー、オークション、マルチステッププロセス、定義された状態での制御された進行が必要な任意のシステムに不可欠です。
pragma solidity ^0.8.0;
contract StateMachine {
// 可能な状態を定義
enum State {
Created,
Active,
Paused,
Completed,
Canceled
}
State public currentState;
address public owner;
uint256 public value;
event StateChanged(State from, State to);
modifier onlyOwner() {
require(msg.sender == , "Not owner");
_;
}
// 状態検証修飾子
modifier inState(State expectedState) {
require(currentState == , "Invalid state");
_;
}
constructor() {
owner = msg.sender;
currentState = State.;
}
// 内部状態遷移関数
function _transitionTo(State newState) internal {
State oldState = ;
currentState = ;
emit StateChanged(, newState);
}
// CreatedからActiveへ遷移
function activate() external onlyOwner inState(State.) {
_transitionTo(State.);
}
// アクティブ操作を一時停止
function pause() external onlyOwner inState(State.Active) {
_transitionTo(State.);
}
// 一時停止状態から再開
function resume() external onlyOwner (State.Paused) {
_transitionTo(State.);
}
// プロセスを完了
function complete() external onlyOwner {
require(
currentState == State. || currentState == State.Paused,
"Cannot complete"
);
_transitionTo(State.);
}
// 操作をキャンセル
function cancel() external onlyOwner {
require(currentState != State., "Already completed");
_transitionTo(State.Canceled);
}
// 状態依存操作
function deposit() external payable inState(State.Active) {
value += ;
}
}