0

How can I make my code sequential, meaning I'd like functions to be performed in a certain order.

Can I make a function not run able till another is run. An example would be great help.

2 Answers 2

0

Here is an idiomatic example that forces functions to be called in a certain order. There is more than one way to do it. Functions check conditions to confirm the transaction is permissible.

pragma solidity 0.5.1;

contract Stages {

    enum Stage { init, two, three, done }

    Stage stage;

    modifier onlyStage (Stage s) {
        require(stage == s, "Wrong step.");
        _;
    }

    function step1() public onlyStage(Stage.init) {
        // do something
        stage = Stage.two;
    }

    function step2() public onlyStage(Stage.two) {
        // do something
        stage = Stage.three;
    }

    function step3() public onlyStage(Stage.three) {
        // do something
        stage = Stage.done;
    }
}

In practice, you would probably have multiple transactions, each at their own stage. For example, a contract to run a game could control multiple games simultaneously. Each game would have properties such as the players, any stake and/or scores, and possibly who's turn it is to play next.

The question is sort of open-ended, so it bears mentioning that any time a function calls out to other contract functions, you are assured that those functions will run in order.

contract A {
  ...
  function inOrder() public {
    b.step1();
    b.step2();
    c.somethingElse(); // step 3
  }
}

Hope it helps.

0

Sounds like you want to use a state machine pattern.

Have a read of the Solidity docs, here.

Contracts often act as a state machine, which means that they have certain stages in which they behave differently or in which different functions can be called. A function call often ends a stage and transitions the contract into the next stage (especially if the contract models interaction).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.