Back to Course

Session 3.3 - Usage Patterns

Applying common smart contract design patterns

Module 3 45 minutes

Learning Objectives

  • Apply common smart contract design patterns
  • Understand when and how to use different patterns
  • Analyze pattern trade-offs and best practices
  • Implement secure and efficient contract designs

Security Patterns

Access Control Pattern

Restrict function access to authorized users only

contract AccessControl {
    address public owner;
    mapping(address => bool) public admins;
    
    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;
    }
    
    modifier onlyAdmin() {
        require(admins[msg.sender], "Not admin");
        _;
    }
    
    function addAdmin(address _admin) public onlyOwner {
        admins[_admin] = true;
    }
}
Circuit Breaker Pattern

Emergency stop mechanism for critical situations

bool public stopped = false;

modifier stopInEmergency() {
    require(!stopped, "Contract is stopped");
    _;
}

function emergencyStop() public onlyOwner {
    stopped = true;
}

Financial Patterns

Withdrawal Pattern
mapping(address => uint) pendingWithdrawals;

function withdraw() public {
    uint amount = pendingWithdrawals[msg.sender];
    pendingWithdrawals[msg.sender] = 0;
    payable(msg.sender).transfer(amount);
}
Rate Limiting
mapping(address => uint) lastWithdrawal;
uint constant COOLDOWN = 1 days;

modifier rateLimited() {
    require(block.timestamp >= 
        lastWithdrawal[msg.sender] + COOLDOWN);
    lastWithdrawal[msg.sender] = block.timestamp;
    _;
}

State Management Patterns

State Machine Pattern
enum State { Created, Locked, Released, Inactive }
State public state;

modifier inState(State _state) {
    require(state == _state, "Invalid state");
    _;
}

modifier transitionTo(State _state) {
    _;
    state = _state;
}

function lock() public inState(State.Created) transitionTo(State.Locked) {
    // Lock logic
}

Pattern Animation Lab

Visualize how patterns change behavior. Choose a pattern and press Play to see how messages, state and funds move across components.

Security Financial State
A
B
Tx

Summary

Key Takeaways
  • Design patterns solve common smart contract problems
  • Security patterns prevent vulnerabilities and attacks
  • Financial patterns handle money transfers safely
  • State patterns manage contract lifecycle effectively
  • Proper pattern usage improves code quality and security

What's Next?

Next, we'll explore DLT-based Smart Contracts across different platforms.