> cat ./linkedin_post.md
[terminal_mode]Smart Contracts: Complete Guide to Self-Executing Code on Blockchain
DATE:2018-06-15|FORMAT:linkedin_post
Nelson Lourenço
Senior Software Engineer | AI & Web Development
2018-06-15•🌐
Smart Contracts: The Complete Enterprise Guide
Smart contracts represent a fundamental shift in how we think about agreements and automation on blockchain networks. Here's everything developers and enterprises need to know.
What Are Smart Contracts?
┌─────────────────────────────────────────────────────────────────────┐
│ SMART CONTRACT CONCEPT │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ TRADITIONAL CONTRACT: SMART CONTRACT: │
│ │
│ ┌─────────────────────┐ ┌─────────────────────┐ │
│ │ Legal Language │ │ Program Code │ │
│ │ Human Lawyers │ │ Self-Executing │ │
│ │ Courts Enforce │ │ Code Enforces │ │
│ │ Manual Execution │ │ Auto Execution │ │
│ │ Trusted Parties │ │ Trustless │ │
│ │ Slow/Costly │ │ Fast/Cheaper │ │
│ └─────────────────────┘ └─────────────────────┘ │
│ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ SMART CONTRACT DEFINITION │ │
│ │ │ │
│ │ "Self-executing contracts with the terms of the │ │
│ │ agreement between buyer and seller being directly │ │
│ │ written into lines of code" │ │
│ │ - Nick Szabo, 1996 │ │
│ │ │ │
│ │ Key Properties: │ │
│ │ • Autonomous (auto-execute when conditions met) │ │
│ │ • Trustless (no intermediary needed) │ │
│ │ • Transparent (visible to all parties) │ │
│ │ • Immutable (cannot be changed once deployed) │ │
│ │ • Deterministic (same input = same output) │ │
│ │ │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Smart Contract Lifecycle
┌─────────────────────────────────────────────────────────────────────┐
│ SMART CONTRACT LIFECYCLE │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ DESIGN │───►│ DEVELOP │───►│ TESTING │───►│ DEPLOY │ │
│ │ │ │ │ │ │ │ │ │
│ │ • Define │ │ • Write │ │ • Unit │ │ • Deploy │ │
│ │ reqs │ │ code │ │ tests │ │ to │ │
│ │ • Model │ │ • Review │ │ • Audit │ │ chain │ │
│ │ logic │ │ • Audit │ │ • Formal│ │ • Verify │ │
│ └──────────┘ └──────────┘ │ verify│ └────┬─────┘ │
│ └──────────┘ │ │
│ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ MAINTAIN │◄───│ UPGRADE │◄───│ MONITOR │◄───│ RUN │ │
│ │ │ │ │ │ │ │ │ │
│ │ • Monitor│ │ • Proxy │ │ • Watch │ │ • Users │ │
│ │ activity│ │ patterns│ │ events│ │ interact│
│ │ • Patch │ │ • Migrate│ │ • Alert │ │ • Funcs │ │
│ │ issues │ │ data │ │ anomalies│ │ execute│ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Solidity Basics
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Basic Token Contract
contract SimpleToken {
string public name = "SimpleToken";
string public symbol = "STK";
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(uint256 _initialSupply) {
totalSupply = _initialSupply * (10 ** uint256(decimals));
balanceOf[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(balanceOf[msg.sender] >= _value, "Insufficient balance");
require(_to != address(0), "Invalid recipient");
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(balanceOf[_from] >= _value, "Insufficient balance");
require(allowance[_from][msg.sender] >= _value, "Allowance exceeded");
require(_to != address(0), "Invalid recipient");
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
}
Common Security Vulnerabilities
┌─────────────────────────────────────────────────────────────────────┐
│ CRITICAL SECURITY VULNERABILITIES │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ 1. REENTRANCY ATTACK │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ The DAO Hack (2016) - $60M stolen │ │
│ │ │ │
│ │ Vulnerable Pattern: │ │
│ │ function withdraw() public { │ │
│ │ uint amount = balances[msg.sender]; │ │
│ │ if (amount > 0) { │ │
│ │ (bool sent, ) = msg.sender.call{value: amount}(""); │ │
│ │ balances[msg.sender] = 0; // Updated AFTER call │ │
│ │ } │ │
│ │ } │ │
│ │ │ │
│ │ Attack Vector: │ │
│ │ 1. Attacker calls withdraw() │ │
│ │ 2. Contract sends ETH to attacker's fallback │ │
│ │ 3. Fallback re-calls withdraw() before balance updated │ │
│ │ 4. Repeat until contract drained │ │
│ │ │ │
│ │ ✅ Mitigation - Checks-Effects-Interactions Pattern: │ │
│ │ function withdraw() public { │ │
│ │ uint amount = balances[msg.sender]; │ │
│ │ require(amount > 0); │ │
│ │ balances[msg.sender] = 0; // UPDATE FIRST! │ │
│ │ (bool sent, ) = msg.sender.call{value: amount}(""); │ │
│ │ require(sent, "Transfer failed"); │ │
│ │ } │ │
│ │ │ │
│ │ ✅ Use ReentrancyGuard: │ │
│ │ contract YourContract is ReentrancyGuard { │ │
│ │ function withdraw() external noReentrancy() { │ │
│ │ // ... │ │
│ │ } │ │
│ │ } │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ 2. INTEGER OVERFLOW/UNDERFLOW │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Before Solidity 0.8.0: │ │
│ │ uint8 public balance; // 0-255 │ │
│ │ balance -= 1; // Can underflow to 255! │ │
│ │ │ │
│ │ ✅ Mitigation (Pre-0.8.0): │ │
│ │ using SafeMath for uint256; │ │
│ │ balance = balance.sub(1); // Reverts on underflow │ │
│ │ │ │
│ │ ✅ Solidity 0.8.0+ - Built-in overflow checks │ │
│ │ balance -= 1; // Automatically reverts! │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ 3. ACCESS CONTROL VULNERABILITIES │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Missing require(msg.sender == owner): │ │
│ │ function emergencyWithdraw() public { │ │
│ │ // No access control! Anyone can call! │ │
│ │ (bool sent, ) = msg.sender.call{value: address(this).balance}(""); │ │
│ │ } │ │
│ │ │ │
│ │ ✅ Mitigation: │ │
│ │ function emergencyWithdraw() public onlyOwner { │ │
│ │ require(msg.sender == owner, "Not authorized"); │ │
│ │ // ... │ │
│ │ } │ │
│ │ │ │
│ │ ✅ Use OpenZeppelin Access Control: │ │
│ │ contract YourContract is AccessControl { │ │
│ │ bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); │ │
│ │ constructor() { │ │
│ │ _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); │ │
│ │ } │ │
│ │ } │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ 4. FRONT-RUNNING ATTACKS │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Problem: Miners see pending transactions │ │
│ │ │ │
│ │ Scenario - Auction Contract: │ │
│ │ 1. User bids 10 ETH on item │ │
│ │ 2. Attacker sees bid, bids 11 ETH higher gas │ │
│ │ 3. Attacker's transaction mined first │ │
│ │ 4. Original bid loses, gas wasted │ │
│ │ │ │
│ │ ✅ Mitigations: │ │
│ │ • Commit-Reveal Schemes (submit hash first, reveal later)│ │
│ │ • Use Flashbots (private transactions) │ │
│ │ • Batch auctions (all bids at once) │ │
│ │ • Decreasing price auctions │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Gas Optimization Strategies
┌─────────────────────────────────────────────────────────────────────┐
│ GAS OPTIMIZATION TECHNIQUES │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ GAS COST REFERENCE: │
│ ┌────────────────────────┬───────────────────────────────────┐ │
│ │ OPERATION │ GAS COST │ │
│ ├────────────────────────┼───────────────────────────────────┤ │
│ │ Storage Write (new) │ 20,000 │ │
│ │ Storage Write (update) │ 5,000 │ │
│ │ Storage Read │ 2,100 │ │
│ │ Memory Allocation │ 3 │ │
│ │ External Call │ 7,000 + calldata │ │
│ │ Event Emission │ 2,000 │ │
│ │ CREATE (new contract) │ 32,000 │ │
│ └────────────────────────┴───────────────────────────────────┘ │
│ │
│ OPTIMIZATION TECHNIQUES: │
│ │
│ 1. PACKING STRUCT MEMBERS │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ ❌ Wasted Gas: │ │
│ │ struct User { │ │
│ │ uint128 balance; // 16 bytes │ │
│ │ uint128 credit; // 16 bytes (same slot) │ │
│ │ address wallet; // 20 bytes (new slot!) │ │
│ │ } │ │
│ │ │ │
│ │ ✅ Optimized: │ │
│ │ struct User { │ │
│ │ address wallet; // 20 bytes │ │
│ │ uint128 balance; // 16 bytes (same slot) │ │
│ │ uint128 credit; // 16 bytes (same slot) │ │
│ │ } │ │
│ │ │ │
│ │ Result: 3 storage slots → 2 slots = 20,000 gas saved │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ 2. USE CALLDATA INSTEAD OF MEMORY │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ ❌ More Expensive: │ │
│ │ function setData(string memory data) external { │ │
│ │ // Memory: copies calldata to memory (copy cost) │ │
│ │ storedData = data; │ │
│ │ } │ │
│ │ │ │
│ │ ✅ Cheaper: │ │
│ │ function setData(string calldata data) external { │ │
│ │ // Calldata: direct access (no copy) │ │
│ │ storedData = data; │ │
│ │ } │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ 3. SHORT-CIRCUIT BOOLEAN EVALUATION │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ ❌ Always evaluates both: │ │
│ │ if (a && b) { ... } │ │
│ │ │ │
│ │ ✅ Short-circuits: │ │
│ │ if (a || b) { ... } │ │
│ │ // If a is true, b is never evaluated │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ 4. CUSTOM ERRORS VS STRINGS │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ ❌ Expensive (deploy and call): │ │
│ │ require(condition, "Long error message with details..."); │ │
│ │ // ~50+ gas per character │ │
│ │ │ │
│ │ ✅ Cheap (just selector): │ │
│ │ error Unauthorized(); │ │
│ │ require(condition, Unauthorized()); │ │
│ │ // Just 4 bytes for error selector │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ 5. UNCHECKED RETURNS FOR LOW-RISK CALLS │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ ❌ Wastes gas checking every call: │ │
│ │ (bool success, ) = externalContract.call(data); │ │
│ │ require(success, "Call failed"); │ │
│ │ │ │
│ │ ✅ Skip check when failure doesn't matter: │ │
│ │ (bool success, ) = externalContract.call(data); │ │
│ │ if (!success) { /* handle silently */ } │ │
│ │ /// OR for external calls we trust: │ │
│ │ externalContract.call(data); // unchecked OK here │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Testing Frameworks
// Hardhat Test Example
const { expect } = require("chai");
const { ethers } = require("hardhat");
describe("SimpleToken", function() {
let token;
let owner;
let addr1;
let addr2;
beforeEach(async function() {
const Token = await ethers.getContractFactory("SimpleToken");
token = await Token.deploy(1000000);
[owner, addr1, addr2] = await ethers.getSigners();
});
describe("Deployment", function() {
it("Should assign total supply to owner", async function() {
const ownerBalance = await token.balanceOf(owner.address);
expect(await token.totalSupply()).to.equal(ownerBalance);
});
it("Should have correct name and symbol", async function() {
expect(await token.name()).to.equal("SimpleToken");
expect(await token.symbol()).to.equal("STK");
});
});
describe("Transfers", function() {
it("Should transfer tokens between accounts", async function() {
await token.transfer(addr1.address, 50);
expect(await token.balanceOf(addr1.address)).to.equal(50);
expect(await token.balanceOf(owner.address)).to.equal(999999950);
});
it("Should emit Transfer event", async function() {
await expect(token.transfer(addr1.address, 50))
.to.emit(token, "Transfer")
.withArgs(owner.address, addr1.address, 50);
});
it("Should revert if sender has insufficient balance", async function() {
await expect(
token.transfer(addr1.address, 9999999999999)
).to.be.revertedWith("Insufficient balance");
});
});
describe("Allowances", function() {
it("Should approve allowance for spender", async function() {
await token.approve(addr1.address, 100);
expect(await token.allowance(owner.address, addr1.address)).to.equal(100);
});
it("Should transferFrom up to allowance", async function() {
await token.approve(addr1.address, 100);
await token.connect(addr1).transferFrom(owner.address, addr2.address, 50);
expect(await token.balanceOf(addr2.address)).to.equal(50);
expect(await token.allowance(owner.address, addr1.address)).to.equal(50);
});
});
});
// Foundry Test Example (Solidity)
contract SimpleTokenTest is Test {
SimpleToken token;
address owner;
address user;
function setUp() public {
token = new SimpleToken(1000000);
owner = msg.sender;
user = makeAddr("user");
}
function testTransfer() public {
vm.prank(owner);
token.transfer(user, 100);
assertEq(token.balanceOf(user), 100);
}
function testTransferFail() public {
vm.prank(owner);
vm.expectRevert("Insufficient balance");
token.transfer(user, 9999999999999);
}
}
Upgrade Patterns
┌─────────────────────────────────────────────────────────────────────┐
│ SMART CONTRACT UPGRADE PATTERNS │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ 1. PROXY PATTERN (Transparent Proxy) │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ ┌─────────────────┐ ┌─────────────────────────┐ │ │
│ │ │ Proxy Contract │ │ Implementation V1 │ │ │
│ │ │ │ │ │ │ │
│ │ │ • delegatecall │──────►│ • All logic here │ │ │
│ │ │ • storage at │ │ • Cannot be upgraded │ │ │
│ │ │ proxy addr │ │ • Upgraded via proxy │ │ │
│ │ │ • upgradeable │ │ │ │ │
│ │ └─────────────────┘ └─────────────────────────┘ │ │
│ │ │ │ │ │
│ │ │ ┌──────────────────┘ │ │
│ │ │ │ │ │
│ │ ▼ ▼ │ │
│ │ ┌─────────────────────────┐ │ │
│ │ │ Implementation V2 │ │ │
│ │ │ • New logic │ │ │
│ │ │ • Deployed separately │ │ │
│ │ │ • Point proxy to here │ │ │
│ │ └─────────────────────────┘ │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ 2. DIAMOND PATTERN (EIP-2535) │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ ┌─────────────────┐ │ │
│ │ │ Diamond │ │ │
│ │ │ │ │ │
│ │ │ • Storage at │ ┌─────────────────────────────┐ │ │
│ │ │ diamond addr │───►│ Facet A (Token Logic) │ │ │
│ │ │ • Multiple │ └─────────────────────────────┘ │ │
│ │ │ facets │ │ │
│ │ │ • Functions │ ┌─────────────────────────────┐ │ │
│ │ │ delegated │───►│ Facet B (NFT Logic) │ │ │
│ │ │ to facets │ └─────────────────────────────┘ │ │
│ │ │ │ │ │
│ │ │ • Upgrade by │ ┌─────────────────────────────┐ │ │
│ │ │ adding/rem │───►│ Facet C (Auction Logic) │ │ │
│ │ │ oving facets │ └─────────────────────────────┘ │ │
│ │ │ │ │ │
│ │ └─────────────────┘ │ │
│ │ │ │
│ │ Benefits: │ │
│ │ • 24KB contract size limit bypassed │ │
│ │ • Modular upgrades │ │
│ │ • Selective function updates │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ 3. DIAMOND PATTERN (EIP-2535) │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ ┌─────────────────────────┐ │ │
│ │ │ OpenZeppelin Upgrades│ │ │
│ │ │ │ │ │
│ │ │ TransparentProxy │ • Admin functions in proxy │ │
│ │ │ ProxyAdmin │ • Same address for all calls│ │
│ │ │ UUPS │ • Logic in implementation │ │
│ │ │ BeaconProxy │ • Multiple proxies, one impl │ │
│ │ │ │ │ │
│ │ └─────────────────────────┘ │ │
│ │ │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Best Practices Summary
┌─────────────────────────────────────────────────────────────────────┐
│ SMART CONTRACT BEST PRACTICES │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ 📋 DEVELOPMENT CHECKLIST: │
│ ✅ Use established frameworks (Hardhat, Foundry) │
│ ✅ Implement comprehensive test coverage (>90%) │
│ ✅ Get professional security audit before mainnet deployment │
│ ✅ Use established libraries (OpenZeppelin) │
│ ✅ Implement circuit breakers / pause mechanisms │
│ ✅ Design upgrade patterns from the start │
│ ✅ Document all public/external functions │
│ ✅ Implement access control on sensitive functions │
│ ✅ Use safe math (Solidity 0.8+ or SafeMath) │
│ ✅ Optimize for gas efficiency in production │
│ ✅ Implement event logging for key actions │
│ ✅ Plan migration path for critical updates │
│ │
│ ⚠️ COMMON MISTAKES TO AVOID: │
│ ❌ Skipping test coverage │
│ ❌ Not getting professional audit │
│ ❌ Hardcoding contract addresses │
│ ❌ Ignoring front-running risks │
│ ❌ Using tx.origin for authentication │
│ ❌ Floating pragma (use specific version) │
│ ❌ Ignoring contract size limits │
│ ❌ Missing emergency stop mechanisms │
│ ❌ Not handling edge cases in business logic │
│ ❌ Assuming deterministic execution (blockhash access) │
│ │
└─────────────────────────────────────────────────────────────────────┘
What smart contract security practices does your team follow? Share your experience!
#SmartContracts #Solidity #Ethereum #BlockchainSecurity #Web3 #DeFi
How is your organization approaching smart contract development and security?
👍357💬104🔁38