Smart Contracts
Solidity programming, contract deployment, security patterns, and testing.
Overview
Smart contracts are self-executing programs on the blockchain.
Basic Solidity Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract SimpleStorage {
uint256 private storedValue;
address public owner;
event ValueChanged(uint256 newValue);
constructor(uint256 initialValue) {
owner = msg.sender;
storedValue = initialValue;
}
function set(uint256 newValue) public {
require(msg.sender == owner, "Only owner can set");
storedValue = newValue;
emit ValueChanged(newValue);
}
function get() public view returns (uint256) {
return storedValue;
}
}
Contract Patterns
Access Control
import "@openzeppelin/contracts/access/Ownable.sol";
contract MyContract is Ownable {
function adminFunction() public onlyOwner {
// Only owner can call
}
}
Reentrancy Guard
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract Vault is ReentrancyGuard {
function withdraw(uint256 amount) public nonReentrant {
require(balance[msg.sender] >= amount);
balance[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
}
}
Testing
// Hardhat test
const { expect } = require("chai");
describe("SimpleStorage", function () {
it("Should store and retrieve value", async function () {
const SimpleStorage = await ethers.getContractFactory("SimpleStorage");
const contract = await SimpleStorage.deploy(100);
expect(await contract.get()).to.equal(100);
await contract.set(200);
expect(await contract.get()).to.equal(200);
});
});
Security Vulnerabilities
| Vulnerability | Description |
|---|---|
| Reentrancy | External call before state update |
| Integer Overflow | Arithmetic overflow |
| Access Control | Missing permissions |
| Front-running | Transaction ordering |
Practice
Deploy and test a smart contract on a testnet.