State machine

State machine is a behavior design pattern.  It allows a contract to alter its behavior when it's internal state changes. A smart contract function call typically moves a contract state from one stage to the next stage. The basic operation of a state machine has two parts:

  • It traverses through a sequence of states, where the next state is determined by the present state, and input conditions.
  • It provides sequences of outputs based upon state transitions.

To illustrate this, let's develop a simple state machine. We will use washing dishes as an example. The process typically is scrub, rinse, dry, scrub, rinse, dry. We defined state machine stages as an enumerated type.  As this is an extensive use case, only the state machine related code is presented. Any logic for detailed action implementation, such as rinse(), dry() and so on are omitted. See the following example:

pragma solidity ^0.4.24;
contract StateMachine {
enum Stages {
INIT,
SCRUB,
RINSE,
DRY,
CLEANUP
}


Stages public stage = Stages.INIT;
modifier atStage(Stages _stage) {
require(stage == _stage);
_;
}
function nextStage() internal {
stage = Stages(uint(stage) + 1);
}
modifier transitionNext() {
_;
nextStage();
}

function scrub() public atStage(Stages.INIT) transitionNext {
// Implement scrub logic here
}


function rinse() public atStage(Stages.SCRUB) transitionNext {
// Implement rinse logic here
}


function dry() public atStage(Stages.SCRUB) transitionNext {
// Implement dry logic here
}


function cleanup() public view atStage(Stages.CLEANUP) {
// Implement dishes cleanup
}
}

We define function modifier atStage to check if the current state allows the stage to run the function. Furthermore, transitionNext modifier will call the internal method nextStage() to move state to next stage.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.89.30