--- name: blockchain-smart-contracts description: Develop secure smart contracts with Solidity for Ethereum and EVM-compatible blockchains. Use for DeFi, NFTs, and decentralized applications. categories: [blockchain, web3] --- # Blockchain Smart Contracts Build secure, efficient smart contracts for decentralized applications. ## Core Concepts - Solidity programming language - EVM (Ethereum Virtual Machine) - Gas optimization - Security best practices - Testing and deployment ## Patterns ### Basic Smart Contract ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract SimpleToken { mapping(address => uint256) public balances; uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 amount); constructor(uint256 _initialSupply) { totalSupply = _initialSupply; balances[msg.sender] = _initialSupply; } function transfer(address to, uint256 amount) public returns (bool) { require(balances[msg.sender] >= amount, "Insufficient balance"); require(to != address(0), "Invalid address"); balances[msg.sender] -= amount; balances[to] += amount; emit Transfer(msg.sender, to, amount); return true; } } ``` ### Security Patterns ```solidity // Checks-Effects-Interactions pattern function withdraw(uint256 amount) public { // Checks require(balances[msg.sender] >= amount, "Insufficient balance"); // Effects balances[msg.sender] -= amount; // Interactions (external calls last) (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed"); } // ReentrancyGuard bool private locked; modifier noReentrant() { require(!locked, "No reentrancy"); locked = true; _; locked = false; } ``` ### Testing with Hardhat ```javascript const { expect } = require("chai"); describe("SimpleToken", function () { it("Should transfer tokens between accounts", async function () { const [owner, addr1] = await ethers.getSigners(); const Token = await ethers.getContractFactory("SimpleToken"); const token = await Token.deploy(1000); await token.transfer(addr1.address, 100); expect(await token.balances(addr1.address)).to.equal(100); }); }); ``` ## Best Practices - Follow Checks-Effects-Interactions pattern - Use SafeMath or Solidity 0.8+ (built-in overflow protection) - Implement access control (Ownable, AccessControl) - Add pausable functionality for emergencies - Optimize gas usage - Conduct security audits - Use standard interfaces (ERC20, ERC721) ## Resources - OpenZeppelin Contracts - Solidity Documentation - ConsenSys Best Practices