Skip to content
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
56 changes: 56 additions & 0 deletions contracts/solidity_patterns/RateLimiter.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

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

contract RateLimiter is NilBase {
uint256 public constant RATE_LIMIT_PERIOD = 1 hours;
uint256 public constant MAX_REQUESTS_PER_PERIOD = 5;

mapping(address => uint256) public lastRequestTimestamp;
mapping(address => uint256) public requestsInCurrentPeriod;

event RequestProcessed(address indexed user, uint256 timestamp);
event PeriodReset(address indexed user, uint256 timestamp);

modifier rateLimited() {
require(_checkRateLimit(msg.sender), "Rate limit exceeded");
_;
}

function _checkRateLimit(address user) internal returns (bool) {
uint256 currentPeriod = block.timestamp / RATE_LIMIT_PERIOD;
uint256 lastPeriod = lastRequestTimestamp[user] / RATE_LIMIT_PERIOD;

if (currentPeriod > lastPeriod) {
requestsInCurrentPeriod[user] = 0;
emit PeriodReset(user, block.timestamp);
}

if (requestsInCurrentPeriod[user] >= MAX_REQUESTS_PER_PERIOD) {
return false;
}

requestsInCurrentPeriod[user]++;
lastRequestTimestamp[user] = block.timestamp;
emit RequestProcessed(user, block.timestamp);

return true;
}

function processRequest() external rateLimited returns (bool) {
// Simulated processing logic
return true;
}

function getRemainingRequests(address user) external view returns (uint256) {
uint256 currentPeriod = block.timestamp / RATE_LIMIT_PERIOD;
uint256 lastPeriod = lastRequestTimestamp[user] / RATE_LIMIT_PERIOD;

if (currentPeriod > lastPeriod) {
return MAX_REQUESTS_PER_PERIOD;
}

return MAX_REQUESTS_PER_PERIOD - requestsInCurrentPeriod[user];
}
}
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!');
41 changes: 41 additions & 0 deletions scripts/create-pattern.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');

const PATTERNS = {
'access': 'AccessRestriction.sol',
'state': 'StateMachine.sol',
'rate': 'RateLimiter.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));