├── 1_Introduction.md ├── 2_gettingStarted.md ├── 3_solidityBasics.md ├── 4_AdvancedSolidityConcepts.md ├── 5_DevelopingSmartContracts.md ├── 6_SecurityBestPractices.md ├── 7_HandsOnProject.md ├── 8_Conclusion.md └── README.md /1_Introduction.md: -------------------------------------------------------------------------------- 1 | # Introduction to Blockchain and Ethereum 2 | 3 | ## Overview of Blockchain Technology 4 | 5 | ### What is Blockchain? 6 | Blockchain is a decentralized digital ledger that records transactions across multiple computers so that the record cannot be altered retroactively. It ensures transparency and security through its distributed nature and cryptographic hashing. 7 | 8 | ### Key Concepts 9 | - **Decentralization:** Unlike traditional centralized databases, a blockchain is maintained by a network of nodes (computers). 10 | - **Immutability:** Once data is recorded in a blockchain, it is extremely difficult to change it. 11 | - **Transparency:** Transactions on a blockchain are visible to all participants, providing a high level of transparency. 12 | 13 | ### How Blockchain Works 14 | 1. **Transaction Initiation:** A user initiates a transaction, which is represented as a block. 15 | 2. **Block Broadcasting:** The block is broadcasted to all nodes in the network. 16 | 3. **Verification:** Nodes validate the transaction using consensus algorithms like Proof of Work (PoW) or Proof of Stake (PoS). 17 | 4. **Adding to the Chain:** Once verified, the block is added to the existing blockchain, becoming a permanent part of the ledger. 18 | 5. **Completion:** The transaction is complete, and the record is immutable and transparent. 19 | 20 | ## Introduction to Ethereum 21 | 22 | ### What is Ethereum? 23 | Ethereum is an open-source, blockchain-based platform that enables developers to build and deploy decentralized applications (dApps). It extends the concept of blockchain by adding a virtual machine capable of executing code of arbitrary algorithmic complexity, known as smart contracts. 24 | 25 | ### Key Components 26 | - **Ether (ETH):** The native cryptocurrency used to power transactions and computational services on the Ethereum network. 27 | - **Smart Contracts:** Self-executing contracts with the terms directly written into code. They automatically enforce and execute terms of an agreement. 28 | - **Ethereum Virtual Machine (EVM):** A runtime environment for smart contracts in Ethereum. It provides a secure and isolated environment to execute code. 29 | 30 | ### How Ethereum Differs from Bitcoin 31 | - **Purpose:** Bitcoin is primarily a digital currency, whereas Ethereum is a platform for decentralized applications and smart contracts. 32 | - **Flexibility:** Ethereum's smart contracts allow for a broader range of applications compared to Bitcoin's scripting language. 33 | - **Consensus Algorithms:** While Bitcoin uses Proof of Work (PoW), Ethereum is transitioning to Proof of Stake (PoS) with Ethereum 2.0. 34 | 35 | ## Smart Contracts 36 | 37 | ### What are Smart Contracts? 38 | Smart contracts are programs that run on the Ethereum blockchain and automatically enforce and execute the terms of an agreement when predefined conditions are met. They are immutable and decentralized, ensuring trust and security without intermediaries. 39 | 40 | ### Key Features 41 | - **Self-executing:** Automatically execute when conditions are met. 42 | - **Immutable:** Once deployed, the code cannot be changed. 43 | - **Transparent:** The contract code and its execution are visible to all participants. 44 | 45 | ### Examples of Smart Contracts 46 | - **Token Contracts:** Create and manage digital tokens. 47 | - **Crowdfunding:** Collect funds from multiple contributors and release them when a target is met. 48 | - **Supply Chain Management:** Track and verify the origin and journey of products. 49 | 50 | ## Conclusion 51 | 52 | Blockchain technology and Ethereum are revolutionizing the way we think about digital transactions and applications. By understanding the fundamentals of blockchain and the capabilities of Ethereum, you can explore the vast potential of decentralized systems and smart contracts. 53 | 54 | --- 55 | 56 | For further learning: 57 | - [Ethereum Whitepaper](https://ethereum.org/en/whitepaper/) 58 | - [Blockchain Basics](https://www.ibm.com/blockchain/what-is-blockchain) 59 | - [Solidity Documentation](https://docs.soliditylang.org/) 60 | -------------------------------------------------------------------------------- /2_gettingStarted.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Solidity 2 | 3 | ## What is Solidity? 4 | Solidity is a high-level, statically-typed programming language designed for writing smart contracts that run on the Ethereum Virtual Machine (EVM). It is similar to JavaScript and influenced by C++ and Python. 5 | 6 | ## Setting Up the Development Environment 7 | 8 | ### Installing Node.js and npm 9 | Node.js and npm (Node Package Manager) are required for running JavaScript code and managing project dependencies. 10 | 11 | 1. **Download and install Node.js:** Visit [Node.js](https://nodejs.org/) and download the LTS version. 12 | 2. **Verify the installation:** 13 | ```bash 14 | node -v 15 | npm -v 16 | ``` 17 | 18 | ### Installing Truffle and Ganache 19 | Truffle is a development framework for Ethereum, and Ganache is a personal blockchain for Ethereum development. 20 | 21 | 1. **Install Truffle:** 22 | ```bash 23 | npm install -g truffle 24 | ``` 25 | 2. **Install Ganache:** Download and install [Ganache](https://www.trufflesuite.com/ganache) for your operating system. 26 | 27 | ### Setting Up MetaMask 28 | MetaMask is a browser extension that acts as a wallet for managing Ethereum accounts and interacting with the Ethereum blockchain. 29 | 30 | 1. **Install MetaMask:** Add the [MetaMask extension](https://metamask.io/) to your browser. 31 | 2. **Create an account:** Follow the instructions to set up a new account and securely store your seed phrase. 32 | 33 | ## Writing the First Smart Contract 34 | 35 | ### Creating a New Project 36 | 1. **Initialize a Truffle project:** 37 | ```bash 38 | mkdir MySolidityProject 39 | cd MySolidityProject 40 | truffle init 41 | ``` 42 | 43 | ### Writing the Contract 44 | 1. **Create a new Solidity file:** `contracts/HelloWorld.sol` 45 | ```solidity 46 | // SPDX-License-Identifier: MIT 47 | pragma solidity ^0.8.0; 48 | 49 | contract HelloWorld { 50 | string public message; 51 | 52 | constructor(string memory _message) { 53 | message = _message; 54 | } 55 | 56 | function setMessage(string memory _message) public { 57 | message = _message; 58 | } 59 | 60 | function getMessage() public view returns (string memory) { 61 | return message; 62 | } 63 | } 64 | ``` 65 | 66 | ### Compiling the Contract 67 | 1. **Compile the contract:** 68 | ```bash 69 | truffle compile 70 | ``` 71 | 72 | ### Deploying the Contract 73 | 1. **Create a migration script:** `migrations/2_deploy_contracts.js` 74 | ```javascript 75 | const HelloWorld = artifacts.require("HelloWorld"); 76 | 77 | module.exports = function (deployer) { 78 | deployer.deploy(HelloWorld, "Hello, Blockchain!"); 79 | }; 80 | ``` 81 | 82 | 2. **Deploy the contract:** 83 | ```bash 84 | truffle migrate 85 | ``` 86 | 87 | ### Interacting with the Contract 88 | 1. **Open Truffle console:** 89 | ```bash 90 | truffle console 91 | ``` 92 | 93 | 2. **Interact with the contract:** 94 | ```javascript 95 | let instance = await HelloWorld.deployed(); 96 | let message = await instance.getMessage(); 97 | console.log(message); // Hello, Blockchain! 98 | await instance.setMessage("Hello, Ethereum!"); 99 | message = await instance.getMessage(); 100 | console.log(message); // Hello, Ethereum! 101 | ``` 102 | 103 | ## Conclusion 104 | You've successfully set up your development environment, written, deployed, and interacted with your first Solidity smart contract. This is the foundation upon which you can build more complex decentralized applications. 105 | 106 | --- 107 | 108 | For further learning: 109 | - [Solidity Documentation](https://docs.soliditylang.org/) 110 | - [Truffle Suite Documentation](https://www.trufflesuite.com/docs) 111 | - [MetaMask Documentation](https://docs.metamask.io/) 112 | -------------------------------------------------------------------------------- /3_solidityBasics.md: -------------------------------------------------------------------------------- 1 | 2 | # Solidity Basics 3 | 4 | ## Solidity Syntax and Structure 5 | 6 | ### Pragma 7 | The `pragma` directive specifies the compiler version for the Solidity code. It helps ensure compatibility between your code and the compiler. 8 | ```solidity 9 | // SPDX-License-Identifier: MIT 10 | pragma solidity ^0.8.0; 11 | ``` 12 | 13 | ### Contract Declaration 14 | A contract is a fundamental building block of Ethereum applications. It is similar to a class in object-oriented programming. 15 | ```solidity 16 | contract SimpleStorage { 17 | // Contract code goes here 18 | } 19 | ``` 20 | 21 | ## Data Types 22 | 23 | ### Value Types 24 | Value types are passed by value and include Booleans, integers, addresses, and fixed-point numbers. 25 | 26 | #### Booleans 27 | ```solidity 28 | bool isReady = true; 29 | ``` 30 | 31 | #### Integers 32 | Solidity supports both signed (`int`) and unsigned (`uint`) integers. 33 | ```solidity 34 | uint8 x = 255; 35 | int y = -10; 36 | ``` 37 | 38 | #### Addresses 39 | Addresses represent Ethereum addresses and can be used to store and manipulate account addresses. 40 | ```solidity 41 | address owner = 0x1234567890123456789012345678901234567890; 42 | ``` 43 | 44 | ### Reference Types 45 | Reference types are more complex types and include arrays, structs, and mappings. 46 | 47 | #### Arrays 48 | ```solidity 49 | uint[] numbers; 50 | string[] names; 51 | ``` 52 | 53 | #### Structs 54 | Structs allow you to create custom data types. 55 | ```solidity 56 | struct Person { 57 | string name; 58 | uint age; 59 | } 60 | 61 | Person public person = Person("Alice", 30); 62 | ``` 63 | 64 | #### Mappings 65 | Mappings are key-value stores for storing data. 66 | ```solidity 67 | mapping(address => uint) public balances; 68 | ``` 69 | 70 | ## Functions 71 | 72 | ### Function Declaration 73 | Functions are used to execute code within a contract. 74 | ```solidity 75 | function set(uint x) public { 76 | // Function code goes here 77 | } 78 | ``` 79 | 80 | ### Function Modifiers 81 | Modifiers can be used to change the behavior of functions. 82 | ```solidity 83 | modifier onlyOwner() { 84 | require(msg.sender == owner, "Not the contract owner"); 85 | _; 86 | } 87 | 88 | function set(uint x) public onlyOwner { 89 | // Function code goes here 90 | } 91 | ``` 92 | 93 | ### View and Pure Functions 94 | View functions do not modify the state and only read data. Pure functions neither read nor modify the state. 95 | ```solidity 96 | function get() public view returns (uint) { 97 | return storedData; 98 | } 99 | 100 | function add(uint a, uint b) public pure returns (uint) { 101 | return a + b; 102 | } 103 | ``` 104 | 105 | ## Events 106 | 107 | ### Defining and Emitting Events 108 | Events allow logging of data that can be accessed through the transaction logs. 109 | ```solidity 110 | event DataStored(uint data); 111 | 112 | function storeData(uint data) public { 113 | storedData = data; 114 | emit DataStored(data); 115 | } 116 | ``` 117 | 118 | ## Error Handling 119 | 120 | ### Require, Assert, Revert 121 | Solidity provides several methods for error handling. 122 | 123 | #### Require 124 | `require` is used to validate conditions and revert if the condition is not met. 125 | ```solidity 126 | function transfer(address to, uint amount) public { 127 | require(balances[msg.sender] >= amount, "Insufficient balance"); 128 | balances[msg.sender] -= amount; 129 | balances[to] += amount; 130 | } 131 | ``` 132 | 133 | #### Assert 134 | `assert` is used to check for conditions that should never be false. It is typically used to catch bugs. 135 | ```solidity 136 | function increment(uint x) public pure returns (uint) { 137 | uint y = x + 1; 138 | assert(y > x); 139 | return y; 140 | } 141 | ``` 142 | 143 | #### Revert 144 | `revert` can be used to flag an error and revert the transaction with a custom error message. 145 | ```solidity 146 | function checkValue(uint value) public pure { 147 | if (value < 0) { 148 | revert("Value must be non-negative"); 149 | } 150 | } 151 | ``` 152 | 153 | ## Conclusion 154 | Understanding the basics of Solidity is essential for writing efficient and secure smart contracts. Mastering data types, functions, events, and error handling will provide a solid foundation for developing decentralized applications on Ethereum. 155 | 156 | --- 157 | 158 | For further learning: 159 | - [Solidity Documentation](https://docs.soliditylang.org/) 160 | - [Ethereum Development Tutorials](https://ethereum.org/en/developers/tutorials/) 161 | -------------------------------------------------------------------------------- /4_AdvancedSolidityConcepts.md: -------------------------------------------------------------------------------- 1 | # Advanced Solidity Concepts 2 | 3 | ## Inheritance 4 | 5 | Inheritance allows one contract to inherit properties and methods from another contract. It promotes code reuse and simplifies contract structure. 6 | 7 | ```solidity 8 | contract Ownable { 9 | address public owner; 10 | 11 | constructor() { 12 | owner = msg.sender; 13 | } 14 | 15 | modifier onlyOwner() { 16 | require(msg.sender == owner, "Only the owner can call this function"); 17 | _; 18 | } 19 | } 20 | 21 | contract MyContract is Ownable { 22 | uint public value; 23 | 24 | function setValue(uint _value) public onlyOwner { 25 | value = _value; 26 | } 27 | } 28 | ``` 29 | 30 | ## Libraries 31 | 32 | Libraries are collections of reusable Solidity functions. They are deployed only once on the blockchain and can be called by other contracts. 33 | 34 | ```solidity 35 | library Math { 36 | function add(uint a, uint b) internal pure returns (uint) { 37 | return a + b; 38 | } 39 | 40 | function subtract(uint a, uint b) internal pure returns (uint) { 41 | require(b <= a, "Subtraction overflow"); 42 | return a - b; 43 | } 44 | } 45 | 46 | contract Calculator { 47 | using Math for uint; 48 | 49 | function calculate(uint x, uint y) public pure returns (uint) { 50 | return x.add(y); 51 | } 52 | } 53 | ``` 54 | 55 | ## Abstract Contracts 56 | 57 | Abstract contracts contain unimplemented functions that must be defined by derived contracts. They are used to define a standard interface. 58 | 59 | ```solidity 60 | abstract contract Token { 61 | function transfer(address recipient, uint amount) public virtual returns (bool); 62 | function balanceOf(address account) public view virtual returns (uint); 63 | } 64 | 65 | contract MyToken is Token { 66 | mapping(address => uint) balances; 67 | 68 | function transfer(address recipient, uint amount) public override returns (bool) { 69 | require(balances[msg.sender] >= amount, "Insufficient balance"); 70 | balances[msg.sender] -= amount; 71 | balances[recipient] += amount; 72 | return true; 73 | } 74 | 75 | function balanceOf(address account) public view override returns (uint) { 76 | return balances[account]; 77 | } 78 | } 79 | ``` 80 | 81 | ## Function Visibility and Access Modifiers 82 | 83 | Solidity provides several function visibility modifiers to control access: 84 | 85 | - **Public:** Visible to all, including external contracts. 86 | - **Internal:** Visible only to the current contract and contracts deriving from it. 87 | - **Private:** Visible only within the current contract. 88 | - **External:** Can only be called externally. 89 | 90 | ```solidity 91 | contract VisibilityExample { 92 | uint private privateVar; 93 | uint internal internalVar; 94 | uint public publicVar; 95 | 96 | function setPrivate(uint _value) private { 97 | privateVar = _value; 98 | } 99 | 100 | function setInternal(uint _value) internal { 101 | internalVar = _value; 102 | } 103 | 104 | function setPublic(uint _value) public { 105 | publicVar = _value; 106 | } 107 | } 108 | ``` 109 | 110 | ## Error Handling and Error Types 111 | 112 | Solidity supports custom error types and robust error handling mechanisms using revert statements and require statements with custom error messages. 113 | 114 | ```solidity 115 | contract ErrorHandling { 116 | function withdraw(uint amount) public { 117 | require(amount <= address(this).balance, "Insufficient balance"); 118 | payable(msg.sender).transfer(amount); 119 | } 120 | 121 | function validate(uint number) public pure returns (uint) { 122 | require(number > 0, "Number must be positive"); 123 | return number; 124 | } 125 | } 126 | ``` 127 | 128 | ## Events and Logging 129 | 130 | Events are used to log important contract interactions. They are useful for debugging, monitoring, and external application integration. 131 | 132 | ```solidity 133 | contract EventExample { 134 | event ItemAdded(address indexed _from, uint _value); 135 | 136 | function addItem(uint _value) public { 137 | // Add item logic 138 | emit ItemAdded(msg.sender, _value); 139 | } 140 | } 141 | ``` 142 | 143 | ## State Variables and Constants 144 | 145 | State variables hold persistent data across function calls and transactions. Constants are variables whose values cannot be changed after initialization. 146 | 147 | ```solidity 148 | contract StateVariables { 149 | uint public stateVar; 150 | uint constant public constantVar = 100; 151 | 152 | constructor(uint _value) { 153 | stateVar = _value; 154 | } 155 | 156 | function setStateVar(uint _newValue) public { 157 | stateVar = _newValue; 158 | } 159 | } 160 | ``` 161 | 162 | ## Gas Optimization 163 | 164 | Gas is the fee required to execute operations on the Ethereum network. Solidity offers several techniques for optimizing gas usage, such as minimizing storage operations and using efficient data structures. 165 | 166 | ```solidity 167 | contract GasOptimization { 168 | uint[] public data; 169 | 170 | function addData(uint _value) public { 171 | data.push(_value); // Expensive operation 172 | } 173 | 174 | // Optimized version 175 | function addDataOptimized(uint _value) public { 176 | uint length = data.length; 177 | if (length == data.length) { 178 | data.push(_value); // Cheap operation 179 | } 180 | } 181 | } 182 | ``` 183 | 184 | ## Security Best Practices 185 | 186 | - **Avoid Reentrancy:** Use the "checks-effects-interactions" pattern to prevent reentrancy attacks. 187 | - **Use SafeMath:** Prevent integer overflow and underflow vulnerabilities. 188 | - **Access Control:** Implement access control mechanisms to restrict function access. 189 | - **Code Audits:** Conduct thorough security audits of smart contracts before deployment. 190 | 191 | ## Conclusion 192 | 193 | Mastering advanced Solidity concepts is crucial for developing secure and efficient decentralized applications on the Ethereum blockchain. These concepts empower developers to create sophisticated smart contracts that can handle complex business logic and interact seamlessly with other contracts and users. 194 | 195 | For further learning: 196 | 197 | - [Solidity Documentation](https://docs.soliditylang.org/) 198 | - [OpenZeppelin Contracts](https://docs.openzeppelin.com/contracts/) 199 | - [Ethereum Development Tutorials](https://ethereum.org/en/developers/tutorials/) 200 | -------------------------------------------------------------------------------- /5_DevelopingSmartContracts.md: -------------------------------------------------------------------------------- 1 | # Developing Smart Contracts 2 | 3 | Developing smart contracts involves writing code in Solidity, testing it thoroughly, and deploying it on the Ethereum blockchain. This section covers the essential steps and considerations for developing robust smart contracts. 4 | 5 | ## Steps for Developing Smart Contracts 6 | 7 | ### 1. Understand Requirements 8 | 9 | Before starting, ensure you have a clear understanding of the requirements for your smart contract. Define its purpose, functionality, and interaction with other contracts or users. 10 | 11 | ### 2. Set Up Development Environment 12 | 13 | #### Tools and IDEs 14 | 15 | Choose an appropriate Integrated Development Environment (IDE) or editor for Solidity development. Popular choices include: 16 | 17 | - [Remix IDE](https://remix.ethereum.org/): A web-based IDE for Solidity smart contract development. 18 | - [Visual Studio Code](https://code.visualstudio.com/) with Solidity extensions: Provides a robust environment with extensions for Solidity syntax highlighting, linting, and debugging. 19 | - [Truffle Suite](https://www.trufflesuite.com/): A development framework for Ethereum that includes tools for compiling, testing, and deploying smart contracts. 20 | 21 | #### Install Dependencies 22 | 23 | If using Truffle or a similar framework, install necessary dependencies and configure your project. 24 | 25 | ### 3. Write Solidity Code 26 | 27 | #### Contract Structure 28 | 29 | Follow a structured approach to writing your contracts. Consider using inheritance, libraries, and modular design to improve code readability and reusability. 30 | 31 | #### Example Contract 32 | 33 | ```solidity 34 | // Example contract: SimpleStorage 35 | contract SimpleStorage { 36 | uint public storedData; 37 | 38 | function set(uint x) public { 39 | storedData = x; 40 | } 41 | 42 | function get() public view returns (uint) { 43 | return storedData; 44 | } 45 | } 46 | ``` 47 | 48 | ### 4. Test Smart Contracts 49 | 50 | Thoroughly test your smart contracts to ensure they behave as expected and handle edge cases. Use unit tests, integration tests, and simulate different scenarios to cover all functionalities. 51 | 52 | #### Testing Frameworks 53 | 54 | - **Truffle Test:** Integrated testing framework provided by Truffle. 55 | - **Remix Testing Plugin:** Allows testing directly in Remix IDE. 56 | - **OpenZeppelin Test Environment:** Includes tools for smart contract testing. 57 | 58 | ### 5. Deploy to Ethereum Blockchain 59 | 60 | #### Testnet Deployment 61 | 62 | Before deploying to the main Ethereum network, deploy your smart contract on a test network (e.g., Ropsten, Rinkeby) to verify its functionality and simulate real-world conditions without using real Ether. 63 | 64 | #### Mainnet Deployment 65 | 66 | When ready, deploy your smart contract to the Ethereum mainnet. Ensure you have sufficient Ether to cover deployment costs (gas fees). 67 | 68 | ### 6. Security Considerations 69 | 70 | #### Best Practices 71 | 72 | - **Avoid Reentrancy:** Use the "checks-effects-interactions" pattern. 73 | - **Use SafeMath:** Prevent integer overflow and underflow vulnerabilities. 74 | - **Access Control:** Implement access control mechanisms to restrict function access. 75 | - **Code Audits:** Conduct thorough security audits of smart contracts. 76 | 77 | ### 7. Interact with Contracts 78 | 79 | Once deployed, interact with your smart contract through web applications, mobile apps, or other smart contracts. Use Ethereum wallets (e.g., MetaMask) to send transactions and interact with contract functions. 80 | 81 | ### 8. Monitor and Maintain 82 | 83 | Monitor your smart contracts for vulnerabilities and performance issues. Update contracts as needed based on user feedback, security audits, and changing requirements. 84 | 85 | ## Conclusion 86 | 87 | Developing smart contracts requires a solid understanding of Solidity, Ethereum blockchain principles, and best practices for security and efficiency. By following structured development processes, testing rigorously, and deploying responsibly, developers can create reliable smart contracts that power decentralized applications (dApps) on Ethereum. 88 | 89 | For further learning: 90 | 91 | - [Solidity Documentation](https://docs.soliditylang.org/) 92 | - [OpenZeppelin Contracts](https://docs.openzeppelin.com/contracts/) 93 | - [Ethereum Developer Resources](https://ethereum.org/en/developers/) 94 | -------------------------------------------------------------------------------- /6_SecurityBestPractices.md: -------------------------------------------------------------------------------- 1 | # Security Best Practices for Smart Contract Development 2 | 3 | Developing secure smart contracts is crucial to protect against vulnerabilities and ensure the integrity of decentralized applications (dApps) on the Ethereum blockchain. Follow these best practices to enhance the security of your Solidity smart contracts. 4 | 5 | ## 1. Avoid Reentrancy Attacks 6 | 7 | Reentrancy occurs when a contract calls back into itself or another contract before completing its initial execution. Use the "checks-effects-interactions" pattern to mitigate reentrancy vulnerabilities. 8 | 9 | ```solidity 10 | contract VulnerableContract { 11 | mapping(address => uint) private balances; 12 | 13 | function withdraw(uint _amount) public { 14 | require(balances[msg.sender] >= _amount); 15 | (bool success, ) = msg.sender.call{value: _amount}(""); 16 | require(success); 17 | balances[msg.sender] -= _amount; 18 | } 19 | } 20 | ``` 21 | 22 | ## 2. Use SafeMath for Arithmetic Operations 23 | 24 | Prevent integer overflow and underflow vulnerabilities by using SafeMath library functions for arithmetic operations on integers. 25 | 26 | ```solidity 27 | import "@openzeppelin/contracts/utils/math/SafeMath.sol"; 28 | 29 | contract SafeMathExample { 30 | using SafeMath for uint256; 31 | 32 | uint256 public total; 33 | 34 | function add(uint256 _value) public { 35 | total = total.add(_value); 36 | } 37 | 38 | function subtract(uint256 _value) public { 39 | total = total.sub(_value); 40 | } 41 | } 42 | ``` 43 | 44 | ## 3. Implement Access Control 45 | 46 | Use access control mechanisms to restrict function access based on user roles or ownership. Define modifiers and require statements to enforce access restrictions. 47 | 48 | ```solidity 49 | contract AccessControl { 50 | address public owner; 51 | 52 | modifier onlyOwner() { 53 | require(msg.sender == owner, "Not the contract owner"); 54 | _; 55 | } 56 | 57 | function changeOwner(address _newOwner) public onlyOwner { 58 | owner = _newOwner; 59 | } 60 | } 61 | ``` 62 | 63 | ## 4. Validate External Input 64 | 65 | Validate and sanitize external input to prevent malicious or unexpected data from compromising contract security. 66 | 67 | ```solidity 68 | contract InputValidation { 69 | function transfer(address _to, uint _amount) public { 70 | require(_to != address(0), "Invalid recipient address"); 71 | require(_amount > 0, "Amount must be greater than zero"); 72 | 73 | // Perform transfer logic 74 | } 75 | } 76 | ``` 77 | 78 | ## 5. Use Latest Solidity Version and Libraries 79 | 80 | Stay updated with the latest Solidity compiler version and utilize secure libraries for common functionalities (e.g., OpenZeppelin Contracts) that have undergone rigorous security audits. 81 | 82 | ```solidity 83 | pragma solidity ^0.8.0; 84 | 85 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 86 | 87 | contract MyToken is ERC20 { 88 | constructor() ERC20("MyToken", "MTK") { 89 | _mint(msg.sender, 1000000 * 10 ** decimals()); 90 | } 91 | } 92 | ``` 93 | 94 | ## 6. Perform Comprehensive Testing 95 | 96 | Thoroughly test smart contracts using both automated tests and manual reviews to identify and fix vulnerabilities before deployment. Test for edge cases, boundary conditions, and potential attack vectors. 97 | 98 | ```solidity 99 | contract TestSmartContract { 100 | function testWithdrawal() public { 101 | // Test withdrawal function with different scenarios 102 | } 103 | 104 | function testAccessControl() public { 105 | // Test access control functionalities 106 | } 107 | } 108 | ``` 109 | 110 | ## 7. Conduct Security Audits 111 | 112 | Engage third-party security auditors or perform internal audits to assess smart contract code for potential security vulnerabilities. Address audit findings promptly before deployment. 113 | 114 | ## 8. Monitor Contract Activity 115 | 116 | Monitor contract activity and events using blockchain explorers and analytics tools to detect any suspicious or unauthorized transactions. 117 | 118 | ## Conclusion 119 | 120 | By following these security best practices, developers can significantly reduce the risk of vulnerabilities and exploits in their Solidity smart contracts. Prioritize security throughout the development lifecycle, from design and coding to testing, deployment, and ongoing maintenance. 121 | 122 | For further learning and resources on secure smart contract development: 123 | 124 | - [OpenZeppelin Contracts](https://docs.openzeppelin.com/contracts/) 125 | - [Solidity Security Considerations](https://docs.soliditylang.org/en/v0.8.7/security-considerations.html) 126 | - [Ethereum Smart Contract Security Best Practices](https://consensys.net/diligence/blog/2019/09/ethereum-smart-contract-security-best-practices/) 127 | -------------------------------------------------------------------------------- /7_HandsOnProject.md: -------------------------------------------------------------------------------- 1 | ### Decentralized Voting System Smart Contract 2 | 3 | #### Step 1: Write the Smart Contracts 4 | 5 | Create two new files: `Voting.sol` and `Ownable.sol`. 6 | 7 | ##### `Ownable.sol` (Contract for Ownership Management) 8 | 9 | ```solidity 10 | // SPDX-License-Identifier: MIT 11 | pragma solidity ^0.8.0; 12 | 13 | contract Ownable { 14 | address private _owner; 15 | 16 | event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); 17 | 18 | constructor() { 19 | _owner = msg.sender; 20 | emit OwnershipTransferred(address(0), _owner); 21 | } 22 | 23 | modifier onlyOwner() { 24 | require(msg.sender == _owner, "Ownable: caller is not the owner"); 25 | _; 26 | } 27 | 28 | function owner() public view returns (address) { 29 | return _owner; 30 | } 31 | 32 | function transferOwnership(address newOwner) public onlyOwner { 33 | require(newOwner != address(0), "Ownable: new owner is the zero address"); 34 | emit OwnershipTransferred(_owner, newOwner); 35 | _owner = newOwner; 36 | } 37 | } 38 | ``` 39 | 40 | **Explanation (`Ownable.sol`):** 41 | 42 | - `Ownable`: This contract manages ownership, allowing only the owner (creator) to perform certain actions. 43 | - `constructor()`: Sets the contract creator as the initial owner. 44 | - `onlyOwner modifier`: Restricts access to functions to only the current owner. 45 | - `transferOwnership(address newOwner)`: Allows the current owner to transfer ownership to another address. 46 | 47 | ##### `Voting.sol` (Decentralized Voting System Contract) 48 | 49 | ```solidity 50 | // SPDX-License-Identifier: MIT 51 | pragma solidity ^0.8.0; 52 | 53 | import "./Ownable.sol"; 54 | 55 | contract Voting is Ownable { 56 | struct Candidate { 57 | uint256 id; 58 | string name; 59 | uint256 voteCount; 60 | } 61 | 62 | mapping(uint256 => Candidate) public candidates; 63 | mapping(address => bool) public voters; 64 | 65 | uint256 public candidatesCount; 66 | 67 | event Voted(uint256 indexed candidateId, address indexed voter); 68 | 69 | constructor() { 70 | addCandidate("Candidate 1"); 71 | addCandidate("Candidate 2"); 72 | } 73 | 74 | function addCandidate(string memory name) private onlyOwner { 75 | candidatesCount++; 76 | candidates[candidatesCount] = Candidate(candidatesCount, name, 0); 77 | } 78 | 79 | function vote(uint256 candidateId) public { 80 | require(candidateId > 0 && candidateId <= candidatesCount, "Invalid candidate ID"); 81 | require(!voters[msg.sender], "Already voted"); 82 | 83 | voters[msg.sender] = true; 84 | candidates[candidateId].voteCount++; 85 | 86 | emit Voted(candidateId, msg.sender); 87 | } 88 | 89 | function getCandidate(uint256 candidateId) public view returns (string memory name, uint256 voteCount) { 90 | require(candidateId > 0 && candidateId <= candidatesCount, "Invalid candidate ID"); 91 | 92 | Candidate memory candidate = candidates[candidateId]; 93 | return (candidate.name, candidate.voteCount); 94 | } 95 | } 96 | ``` 97 | 98 | **Explanation (`Voting.sol`):** 99 | 100 | - `Voting`: This contract implements a decentralized voting system. 101 | - `Candidate struct`: Defines a structure to store candidate information including ID, name, and vote count. 102 | - `candidates mapping`: Maps candidate IDs to `Candidate` structs. 103 | - `voters mapping`: Maps addresses to a boolean indicating whether they have voted. 104 | - `candidatesCount`: Stores the total number of candidates. 105 | - `event Voted`: Logs voting events. 106 | - `constructor()`: Initializes the contract by adding two candidates. 107 | - `addCandidate(string memory name) private onlyOwner`: Function to add a new candidate. Only the contract owner can add candidates. 108 | - `vote(uint256 candidateId) public`: Function for voters to cast their vote for a candidate. 109 | - `getCandidate(uint256 candidateId) public view returns (string memory name, uint256 voteCount)`: Function to retrieve candidate information by ID. 110 | 111 | #### Step 2: Compile the Smart Contracts 112 | 113 | 1. **Using Remix IDE:** 114 | - Go to [Remix IDE](https://remix.ethereum.org/). 115 | - Create two new files: `Voting.sol` and `Ownable.sol`. 116 | - Paste the respective Solidity code into each file. 117 | - Click on the "Solidity Compiler" tab. 118 | - Click "Compile Voting.sol" and ensure both contracts compile without errors. 119 | 120 | #### Step 3: Deploy and Interact with the Smart Contract 121 | 122 | 1. **Deploying and Interacting in Remix:** 123 | - In Remix, go to the "Deploy & Run Transactions" tab. 124 | - Deploy the `Voting` contract. Ensure you have selected a suitable environment (e.g., JavaScript VM for testing or Injected Web3/MetaMask for deployment on a real network). 125 | - Interact with the contract: 126 | - Use the `addCandidate` function to add candidates. 127 | - Use the `vote` function to cast votes for candidates. 128 | - Use the `getCandidate` function to retrieve candidate information. 129 | 130 | #### Step 4: Testing and Deployment 131 | 132 | 1. **Testing and Deployment:** 133 | - Test the functionality of the voting system using Remix's testing tools or by writing automated tests using frameworks like Truffle. 134 | - Deploy the contract to a real Ethereum network (testnet or mainnet) using MetaMask or another Web3 provider. 135 | 136 | ### Summary 137 | 138 | This decentralized voting system project demonstrates more advanced Solidity concepts, including structs, mappings, modifiers (`onlyOwner`), events, and interactions between multiple contracts (`Voting` and `Ownable`). It provides a practical example of how Solidity can be used to implement real-world applications on the Ethereum blockchain, such as voting systems with transparent and auditable results. 139 | -------------------------------------------------------------------------------- /8_Conclusion.md: -------------------------------------------------------------------------------- 1 | ## Conclusion 2 | 3 | ### Recap of Key Concepts 4 | 5 | Throughout this workshop, we've covered essential aspects of Solidity and smart contract development on the Ethereum blockchain. Here's a recap of key concepts: 6 | 7 | - **Solidity Basics**: Understanding the syntax, data types, functions, and modifiers in Solidity. 8 | - **Advanced Concepts**: Inheritance, libraries, modifiers, and security best practices. 9 | - **Hands-on Experience**: Writing, deploying, and interacting with smart contracts. 10 | - **Security Best Practices**: Techniques to prevent vulnerabilities like reentrancy, integer overflows, and access control. 11 | 12 | ### Further Learning Resources 13 | 14 | To continue your journey in Solidity and blockchain development, explore these resources: 15 | 16 | - **Solidity Documentation**: [Solidity Documentation](https://docs.soliditylang.org/) - Official documentation for Solidity with comprehensive guides and references. 17 | - **Online Courses**: Platforms like [Coursera](https://www.coursera.org/), [Udemy](https://www.udemy.com/), and [CryptoZombies](https://cryptozombies.io/) offer courses on blockchain and Solidity development. 18 | - **Community and Forums**: Engage with the blockchain community on platforms such as [Stack Exchange - Ethereum](https://ethereum.stackexchange.com/), [Reddit - r/ethereum](https://www.reddit.com/r/ethereum/), and [GitHub - Ethereum](https://github.com/ethereum) for discussions, Q&A, and collaboration. 19 | 20 | ### Keep Exploring! 21 | 22 | Blockchain technology and smart contracts are rapidly evolving fields. Keep practicing, exploring new concepts, and staying updated with the latest developments to harness the full potential of decentralized applications (dApps) on Ethereum. 23 | 24 | Thank you for joining us in this workshop. Happy coding! 25 | 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Solidity Workshop 2 | 3 | ## [Introduction to Blockchain and Ethereum](1_Introduction.md) 4 | - Overview of Blockchain Technology 5 | - Introduction to Ethereum 6 | - Smart Contracts 7 | 8 | ## [Getting Started with Solidity](2_gettingStarted.md) 9 | - What is Solidity? 10 | - Setting Up the Development Environment 11 | - Installing Node.js and npm 12 | - Installing Truffle and Ganache 13 | - Setting Up MetaMask 14 | - Writing the First Smart Contract 15 | 16 | ## [Solidity Basics](3_solidityBasics.md) 17 | - Solidity Syntax and Structure 18 | - Pragma 19 | - Contract Declaration 20 | - Data Types 21 | - Value Types (Booleans, Integers, Addresses, Fixed Point Numbers) 22 | - Reference Types (Arrays, Structs, Mappings) 23 | - Functions 24 | - Function Declaration 25 | - Function Modifiers 26 | - View and Pure Functions 27 | 28 | ## [Advanced Solidity Concepts](4_AdvancedSolidityConcepts.md) 29 | - Inheritance 30 | - Libraries 31 | - Events 32 | - Error Handling 33 | - require, assert, revert 34 | 35 | ## [Developing Smart Contracts](5_DevelopingSmartContracts.md) 36 | - Creating and Deploying Contracts 37 | - Interacting with Contracts 38 | - Using Web3.js 39 | - Using Truffle 40 | - Testing Contracts 41 | - Writing Test Cases with Truffle 42 | - Using Ganache for Testing 43 | 44 | ## [Security Best Practices](6_SecurityBestPractices.md) 45 | - Common Vulnerabilities 46 | - Reentrancy 47 | - Overflow and Underflow 48 | - Access Control 49 | - Best Practices 50 | - Use SafeMath Library 51 | - Avoid Using tx.origin 52 | - Check for External Contract Calls 53 | 54 | ## [Hands-on Session](7_HandsOnProject.md) 55 | - Building a Simple DApp 56 | - Defining the Requirements 57 | - Writing the Smart Contract 58 | - Deploying the Contract 59 | - Interacting with the Contract through a Frontend 60 | - Q&A and Troubleshooting 61 | 62 | ## [Conclusion](8_Conclusion.md) 63 | - Recap of Key Concepts 64 | - Further Learning Resources 65 | - Solidity Documentation 66 | - Online Courses 67 | - Community and Forums 68 | --------------------------------------------------------------------------------