State Machine Pattern in Solidity


During developing a smart contract sometime we need to manage the different stages and execute and restrict method according to that state/stage of the smart contract.

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;


contract StateMachinePattern{
    
    enum State {
        FIRST_STAGE,
        SECOND_STAGE,
        THIRD_STAGE
    }
    
    error functionInvalidAtThisStage();
    
    State state = State.FIRST_STAGE;
    
    
    modifier AtState(State _state){
        if(state != _state)
        revert functionInvalidAtThisStage();
        
        _;
    }
    
    function nextStage() internal{
        state = State(uint(state) + 1);
    }
    
    function a()public AtState(State.FIRST_STAGE){
        //body
        nextStage();
    }
    
    function b()public AtState(State.SECOND_STAGE){
        //body
        nextStage();
    }
    
    function c()public AtState(State.THIRD_STAGE){
        //body
        
    }
}

,