Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a State Machine Pattern #21

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions contracts/solidity_patterns/StateMachine.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

import "@nilfoundation/smart-contracts/contracts/NilBase.sol";

contract StateMachine is NilBase {
enum Stages {
Initialize,
Processing,
Completed,
Failed
}

Stages public currentStage;

uint256 public processValue;
mapping(address => bool) public hasParticipated;

event StageAdvanced(Stages newStage);
event ProcessValueUpdated(uint256 newValue);

modifier atStage(Stages _stage) {
require(currentStage == _stage, "Invalid stage");
_;
}

modifier transitionAfter() {
_;
_nextStage();
}

constructor() {
currentStage = Stages.Initialize;
}

function startProcess() external atStage(Stages.Initialize) transitionAfter {
processValue = 0;
emit ProcessValueUpdated(processValue);
}

function participate() external atStage(Stages.Processing) {
require(!hasParticipated[msg.sender], "Already participated");

hasParticipated[msg.sender] = true;
processValue += 1;

emit ProcessValueUpdated(processValue);

if (processValue >= 5) {
currentStage = Stages.Completed;
emit StageAdvanced(Stages.Completed);
}
}

function _nextStage() internal {
currentStage = Stages(uint(currentStage) + 1);
emit StageAdvanced(currentStage);
}

function reset() external onlyInternal {
require(currentStage == Stages.Completed || currentStage == Stages.Failed,
"Can only reset from Completed or Failed state");
currentStage = Stages.Initialize;
processValue = 0;
emit StageAdvanced(Stages.Initialize);
emit ProcessValueUpdated(processValue);
}
}
13 changes: 13 additions & 0 deletions scripts/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,22 @@ function copyFile(srcFilePath, destFilePath) {
}
}

function addPatternCommand() {
const packageJsonPath = path.join(projectPath, 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));

// Add create-pattern command to scripts
packageJson.scripts = packageJson.scripts || {};
packageJson.scripts['create-pattern'] = 'node scripts/create-pattern.js';

fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
}

createPackageJson(templatePath, projectPath);
copyFile('.env.example', '.env');
copyFile('ignition/modules/Incrementer.ts', 'ignition/modules/Incrementer.ts');
copyFile('contracts/Incrementer.sol', 'contracts/Incrementer.sol');
copyFile('scripts/create-pattern.js', 'scripts/create-pattern.js');
addPatternCommand();

console.log('Project setup complete!');
40 changes: 40 additions & 0 deletions scripts/create-pattern.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');

const PATTERNS = {
'access': 'AccessRestriction.sol',
'state': 'StateMachine.sol',
'guard': 'GuardCheck.sol',
'proxy': 'ProxyDelegate.sol',
'check': 'CheckEffectsInteraction.sol'
};

function createPattern(patternName, projectPath) {
if (!PATTERNS[patternName]) {
console.error(`Invalid pattern name. Available patterns: ${Object.keys(PATTERNS).join(', ')}`);
process.exit(1);
}

const templatePath = path.join(__dirname, '..', 'contracts', 'solidity_patterns', PATTERNS[patternName]);
const destPath = path.join(projectPath, 'contracts', 'patterns', PATTERNS[patternName]);

// Create directories if they don't exist
fs.mkdirSync(path.join(projectPath, 'contracts', 'patterns'), { recursive: true });

// Copy pattern file
fs.copyFileSync(templatePath, destPath);
console.log(`Created ${patternName} pattern at: ${destPath}`);
}

// Get command line arguments
const patternName = process.argv[2];
const projectDir = process.argv[3] || '.';

if (!patternName) {
console.error('Please specify a pattern name');
console.log(`Available patterns: ${Object.keys(PATTERNS).join(', ')}`);
process.exit(1);
}

createPattern(patternName.toLowerCase(), path.resolve(projectDir));