Blockchain technology has revolutionized the way we think about digital transactions. One of the key components of blockchain is smart contracts. Smart contracts are self-executing contracts with the terms of the agreement directly written into lines of code. They automatically enforce and execute the terms of an agreement when predetermined conditions are met.

In this tutorial, we will explore some common patterns used in smart contracts. These patterns can help you understand how to write effective and secure smart contracts.

Common Patterns

1. Immutable Data Storage

Smart contracts are designed to store data immutably. This means once data is written to the blockchain, it cannot be changed or deleted. A common pattern for storing immutable data is to use a mapping or struct.

struct Data {
    uint256 id;
    string value;
}

mapping(uint256 => Data) public dataMap;

2. Access Control

Access control is crucial in smart contracts to ensure that only authorized users can execute certain functions. One way to achieve this is by using access modifiers such as public, private, and external.

contract AccessControl {
    address public owner;

    constructor() {
        owner = msg.sender;
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;
    }

    function changeOwner(address _newOwner) public onlyOwner {
        owner = _newOwner;
    }
}

3. Event Logging

Events are used to log actions that occur within a smart contract. They are an essential part of smart contract development as they allow external applications to react to changes on the blockchain.

event DataStored(address indexed _address, uint256 _id, string _value);

function storeData(uint256 _id, string memory _value) public {
    dataMap[_id] = Data(_id, _value);
    emit DataStored(msg.sender, _id, _value);
}

4. Time Locks

Time locks are a mechanism to prevent a contract from being executed until a certain point in time. This can be useful for creating defi applications where you want to release funds after a certain period.

contract TimeLock {
    uint256 public unlockTime;

    constructor(uint256 _unlockTime) {
        unlockTime = _unlockTime;
    }

    function lock() public {
        require(block.timestamp < unlockTime, "Lock period not expired");
    }
}

Further Reading

For more information on smart contract development, check out our comprehensive guide on Solidity Best Practices.

Smart Contract Image