From b61e48d8ddc1d8c5fb3b46ef4260a08b9731f596 Mon Sep 17 00:00:00 2001 From: Asharib Ali Date: Tue, 2 May 2023 21:28:06 +0500 Subject: [PATCH 1/2] add learn solidity in baby-steps --- .../step05_solidity/step00_Details/readme.md | 41 ++++++ .../step01_Introduction_to_Solidity/readme.md | 74 ++++++++++ .../step02_Solidity_Data_Types/readme.md | 128 ++++++++++++++++++ .../readme.md | 70 ++++++++++ .../step04_Solidity_Functions/readme.md | 76 +++++++++++ .../readme.md | 81 +++++++++++ .../step06_Solidity_Events/readme.md | 62 +++++++++ .../step07_Solidity_Inheritance/readme.md | 126 +++++++++++++++++ .../step08_Solidity_Libraries/readme.md | 47 +++++++ .../step09_Solidity_Testing/readme.md | 45 ++++++ .../step10_Solidity_Deployment/readme.md | 65 +++++++++ 11 files changed, 815 insertions(+) create mode 100644 stepxx_web3/step05_solidity/step00_Details/readme.md create mode 100644 stepxx_web3/step05_solidity/step01_Introduction_to_Solidity/readme.md create mode 100644 stepxx_web3/step05_solidity/step02_Solidity_Data_Types/readme.md create mode 100644 stepxx_web3/step05_solidity/step03_Solidity_Variables_and_Constants/readme.md create mode 100644 stepxx_web3/step05_solidity/step04_Solidity_Functions/readme.md create mode 100644 stepxx_web3/step05_solidity/step05_Solidity_Control_Structures/readme.md create mode 100644 stepxx_web3/step05_solidity/step06_Solidity_Events/readme.md create mode 100644 stepxx_web3/step05_solidity/step07_Solidity_Inheritance/readme.md create mode 100644 stepxx_web3/step05_solidity/step08_Solidity_Libraries/readme.md create mode 100644 stepxx_web3/step05_solidity/step09_Solidity_Testing/readme.md create mode 100644 stepxx_web3/step05_solidity/step10_Solidity_Deployment/readme.md diff --git a/stepxx_web3/step05_solidity/step00_Details/readme.md b/stepxx_web3/step05_solidity/step00_Details/readme.md new file mode 100644 index 00000000..c6e7f3db --- /dev/null +++ b/stepxx_web3/step05_solidity/step00_Details/readme.md @@ -0,0 +1,41 @@ +# STEP 1: Introduction to Solidity + +Solidity is a programming language used to write smart contracts on the Ethereum blockchain. In order to write smart contracts in Solidity, you will need to have some programming knowledge. In this README, we will cover some basic concepts in Solidity. + +# STEP 2: Solidity Data Types + +In Solidity, there are several data types that you can use to declare variables. These data types include integers, booleans, strings, addresses, and more. In this README, we will cover these data types and how to use them in your smart contracts. + +# STEP 3: Solidity Variables and Constants + +In Solidity, you can declare variables and constants to store data. Variables can be changed during the execution of your smart contract, while constants cannot. In this README, we will cover how to declare variables and constants in Solidity. + +# STEP 4: Solidity Functions + +Functions are an important part of Solidity smart contracts. They are used to define the behavior of your smart contract. In this README, we will cover how to declare and use functions in Solidity. + +# STEP 5: Solidity Control Structures + +Control structures are used to control the flow of your Solidity smart contract. They allow you to make decisions based on certain conditions or to repeat certain actions multiple times. In this README, we will cover how to use control structures in Solidity. + +# STEP 6: Solidity Events + +Events are used to emit information from your Solidity smart contract to the Ethereum blockchain. They allow you to track the execution of your smart contract and notify interested parties of certain events. In this README, we will cover how to declare and use events in Solidity. + +# STEP 7: Solidity Inheritance + +Inheritance is a way to reuse code in Solidity smart contracts. It allows you to create a new smart contract that inherits the properties of an existing contract. In this README, we will cover how to use inheritance in Solidity. + +# STEP 8: Solidity Libraries + +Libraries are a way to reuse code in Solidity smart contracts. They are similar to contracts, but they are not deployed on the blockchain. In this README, we will cover how to use libraries in Solidity. + +# STEP 9: Solidity Testing + +Testing is an important part of software development, and Solidity smart contracts are no exception. In this README, we will cover how to write tests for your Solidity smart contracts using the hardhat testing framework. + +# STEP 10: Solidity Deployment + +Once you have written your Solidity smart contract and tested it, you will need to deploy it to the Ethereum blockchain. In this README, we will cover how to deploy your Solidity smart contract using the Remix IDE and the Truffle framework. + +I hope these 10 READMEs will provide you with a good foundation to learn and start writing Solidity smart contracts. diff --git a/stepxx_web3/step05_solidity/step01_Introduction_to_Solidity/readme.md b/stepxx_web3/step05_solidity/step01_Introduction_to_Solidity/readme.md new file mode 100644 index 00000000..2434637b --- /dev/null +++ b/stepxx_web3/step05_solidity/step01_Introduction_to_Solidity/readme.md @@ -0,0 +1,74 @@ +# Introduction to Solidity + +Solidity is a programming language used to write smart contracts on the Ethereum blockchain. Smart contracts are self-executing contracts with the terms of the agreement between buyer and seller being directly written into lines of code. Smart contracts allow for trustless transactions to take place without the need for intermediaries, making them a powerful tool for decentralized applications (dApps) and blockchain-based solutions. + +Solidity was developed by the Ethereum Foundation and is one of the most popular programming languages for writing smart contracts. It is a high-level language that is influenced by C++, Python, and JavaScript. It is designed to be easy to learn for developers with a background in object-oriented programming. + +## Features of Solidity + +Solidity comes with several features that make it suitable for writing smart contracts. These include: + +- **Static Typing:** Solidity is a statically typed language, which means that variable types are checked at compile time, ensuring greater accuracy and fewer errors. +- **Object-Oriented Programming (OOP):** Solidity supports OOP concepts such as inheritance, encapsulation, and polymorphism, allowing for code reuse and better organization. +- **Ethereum Integration:** Solidity is designed to work seamlessly with the Ethereum Virtual Machine (EVM), making it easy to deploy and execute smart contracts on the Ethereum blockchain. +- **Security:** Solidity comes with several security features to help prevent common vulnerabilities such as reentrancy attacks and integer overflow/underflow. + +## Getting Started with Solidity + +To get started with Solidity, follow these steps: + +1. **Learn programming concepts:** You will need a basic understanding of programming concepts such as variables, functions, and control structures. + Certainly! Here's an example of how to set up a development environment for writing Solidity code on your local machine: + +## Setting up a Solidity Development Environment + +### Step 1: Install Node.js + +Node.js is a JavaScript runtime that allows you to run JavaScript code outside of a web browser. It's required for running various tools and packages that you'll use for Solidity development. + +To install Node.js, follow these steps: + +1. Go to the [Node.js download page](https://nodejs.org/en/download/) and download the appropriate version for your operating system. +2. Run the installer and follow the prompts to complete the installation. + +### Step 2: Install a Solidity Compiler + +A Solidity compiler is required to convert your Solidity code into bytecode that can be executed on the Ethereum Virtual Machine (EVM). + +There are several Solidity compilers available, but one of the most popular is `solc`, which is a command-line tool. To install `solc`, follow these steps: + +1. Open a terminal or command prompt. +2. Run the following command to install `solc`: + +``` +npm install -g solc +``` + +### Step 3: Install a Development Environment + +There are several development environments available for Solidity development, including Remix, Truffle, and Embark. + +For this example, we'll use Remix, which is a web-based Solidity IDE. To use Remix, follow these steps: + +1. Go to the [Remix website](https://remix.ethereum.org/) and select "Start Remix IDE". +2. You should now see the Remix IDE in your web browser. You can start writing Solidity code in the editor on the left-hand side. + +### Step 4: Test your Development Environment + +To test your development environment, try compiling a simple Solidity contract in Remix. + +1. In the Remix IDE, create a new file and name it `simple_contract.sol`. +2. Copy and paste the following code into the file: + +``` +pragma solidity ^0.8.0; + +contract SimpleContract { + string public message = "Hello, world!"; +} +``` + +3. Click the "Compile" button in the Remix IDE. If there are no errors, you should see a green checkmark next to the file name. +4. You can now deploy the contract by clicking the "Deploy & Run Transactions" button. Once the contract is deployed, you can interact with it by calling its functions. + +Congratulations! You now have a working Solidity development environment on your local machine. From here, you can start experimenting with more complex Solidity contracts and building decentralized applications on the Ethereum blockchain. diff --git a/stepxx_web3/step05_solidity/step02_Solidity_Data_Types/readme.md b/stepxx_web3/step05_solidity/step02_Solidity_Data_Types/readme.md new file mode 100644 index 00000000..b490aba9 --- /dev/null +++ b/stepxx_web3/step05_solidity/step02_Solidity_Data_Types/readme.md @@ -0,0 +1,128 @@ +## Solidity Data Types + +Solidity is a statically-typed language, which means that all variables must have a defined data type. There are several data types available in Solidity, each with its own specific use case. + +### Boolean + +The `bool` data type is used to represent boolean values (`true` or `false`). For example: + +``` +bool myBool = true; +``` + +### Integer + +The `int` data type is used to represent signed integers, while the `uint` data type is used to represent unsigned integers. You can specify the number of bits used to represent the integer by including a number after the data type. For example: + +``` +int8 myInt8 = -128; +uint256 myUint256 = 123456789; +``` + +### Address + +The `address` data type is used to represent Ethereum addresses. Addresses are 20 bytes long and are typically represented in hexadecimal notation. For example: + +``` +address myAddress = 0x1234567890123456789012345678901234567890; +``` + +### String + +The `string` data type is used to represent arbitrary-length UTF-8 encoded strings. For example: + +``` +string myString = "Hello, world!"; +``` + +### Bytes + +The `bytes` data type is used to represent byte arrays. You can specify the number of bytes used to represent the array by including a number after the data type. For example: + +``` +bytes32 myBytes32 = 0x1234567890123456789012345678901234567890123456789012345678901234; +``` + +### Structs + +Structs are used to define custom data types that contain multiple variables. For example: + +``` +struct Person { + string name; + uint age; +} + +Person myPerson = Person("Alice", 30); +``` + +### Arrays + +Arrays are used to represent collections of values of the same data type. There are two types of arrays in Solidity: fixed-size arrays and dynamic arrays. For example: + +``` +uint[3] myFixedArray; +myFixedArray[0] = 1; +myFixedArray[1] = 2; +myFixedArray[2] = 3; + +uint[] myDynamicArray; +myDynamicArray.push(1); +myDynamicArray.push(2); +myDynamicArray.push(3); +``` + +### Mapping + +Mappings are used to associate values of one data type (the key) with values of another data type (the value). For example: + +``` +mapping(address => uint) public balances; +balances[0x123...] = 1000; +``` + +In this example, the mapping associates Ethereum addresses with account balances. + +## Example + +Here's an example that demonstrates the use of multiple data types in a Solidity contract: + +``` +pragma solidity ^0.8.0; + +contract MyContract { + bool public myBool = true; + int8 public myInt8 = -128; + uint256 public myUint256 = 123456789; + address public myAddress = 0x1234567890123456789012345678901234567890; + string public myString = "Hello, world!"; + bytes32 public myBytes32 = 0x1234567890123456789012345678901234567890123456789012345678901234; + Person public myPerson = Person("Alice", 30); + uint[3] public myFixedArray; + uint[] public myDynamicArray; + mapping(address => uint) public balances; + + struct Person { + string name; + uint age; + } + + constructor() { + myFixedArray[0] = 0; + myFixedArray[1] = 1; + myFixedArray[2] = 2; + + myDynamicArray.push(1); + myDynamicArray.push(2); + myDynamicArray.push(3); + + balances[0x123...] = 1000; +}} + +``` + +In this example, we've defined a Solidity contract called `MyContract` that includes variables of several different data types. We've also included a constructor function that initializes some of these variables. + +Note that we've defined a `Person` struct type, and we've created a variable `myPerson` of this type. We've also defined a mapping that associates Ethereum addresses with account balances. + +By using these different data types, we can create powerful and flexible smart contracts that can interact with the Ethereum blockchain in a wide variety of ways. diff --git a/stepxx_web3/step05_solidity/step03_Solidity_Variables_and_Constants/readme.md b/stepxx_web3/step05_solidity/step03_Solidity_Variables_and_Constants/readme.md new file mode 100644 index 00000000..8e3f204c --- /dev/null +++ b/stepxx_web3/step05_solidity/step03_Solidity_Variables_and_Constants/readme.md @@ -0,0 +1,70 @@ +## Solidity Variables and Constants + +In Solidity, variables are used to store data that can be manipulated or changed during the execution of a smart contract, while constants are used to store data that cannot be changed. + +### Variables + +Variables in Solidity are declared using the `var` or data type keyword, followed by the variable name. For example: + +``` +uint256 myUint = 123; +bool myBool = true; +address myAddress = 0x1234567890123456789012345678901234567890; +``` + +Once a variable is declared, its value can be changed using the assignment operator `=`. For example: + +``` +myUint = 456; +``` + +Solidity also supports arithmetic and logical operations on variables, such as addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), and modulus (`%`). For example: + +``` +uint256 a = 5; +uint256 b = 2; +uint256 c = a + b; // c is now 7 +``` + +### Constants + +Constants in Solidity are declared using the `constant` keyword, followed by the data type and variable name. For example: + +``` +uint256 constant MY_CONST = 123; +``` + +Once a constant is declared, its value cannot be changed. Constants are typically used to store values that are known at compile time and do not need to be modified during the execution of a smart contract. + +### Example + +Here's an example that demonstrates the use of variables and constants in a Solidity contract: + +``` +pragma solidity ^0.8.0; + +contract MyContract { + uint256 public myUint = 123; + bool public myBool = true; + address public myAddress = 0x1234567890123456789012345678901234567890; + uint256 constant MY_CONST = 456; + + function setMyUint(uint256 _myUint) public { + myUint = _myUint; + } + + function getMyUint() public view returns (uint256) { + return myUint; + } + + function doSomething() public { + myUint = myUint + MY_CONST; + } +} +``` + +In this example, we've defined a Solidity contract called `MyContract` that includes both variables and a constant. We've defined a `myUint` variable that can be changed using the `setMyUint()` function, and a `getMyUint()` function that allows us to retrieve the current value of `myUint`. + +We've also defined a `doSomething()` function that modifies the value of `myUint` by adding the value of the `MY_CONST` constant. + +By using variables and constants, we can create smart contracts that are both flexible and secure, ensuring that data is stored and manipulated correctly and consistently. diff --git a/stepxx_web3/step05_solidity/step04_Solidity_Functions/readme.md b/stepxx_web3/step05_solidity/step04_Solidity_Functions/readme.md new file mode 100644 index 00000000..af7509e4 --- /dev/null +++ b/stepxx_web3/step05_solidity/step04_Solidity_Functions/readme.md @@ -0,0 +1,76 @@ +## Solidity Functions + +Functions in Solidity are used to encapsulate and perform specific tasks within a smart contract. They can be called internally by other functions within the same contract, or externally by other contracts or external accounts on the Ethereum network. + +### Function Declaration + +Functions in Solidity are declared using the `function` keyword, followed by the function name and any input parameters in parentheses. For example: + +``` +function myFunction(uint256 myParam) public { + // function code here +} +``` + +The `public` keyword indicates that the function can be called from other contracts or external accounts on the Ethereum network. + +### Function Visibility + +Functions in Solidity can have different levels of visibility, which determines who can call the function. The different levels of visibility are: + +- `public`: can be called from anywhere +- `private`: can only be called from within the same contract +- `internal`: can only be called from within the same contract or from contracts that inherit from it +- `external`: can only be called from outside the contract + +### Function Modifiers + +Function modifiers in Solidity are used to modify the behavior of a function. They are declared using the `modifier` keyword, followed by the modifier name. For example: + +``` +modifier onlyOwner() { + require(msg.sender == owner, "Only the contract owner can call this function."); + _; +} +``` + +The `require()` statement in this modifier ensures that the function can only be called by the owner of the contract. The `_` placeholder indicates where the modified function code will be inserted. + +### Example + +Here's an example that demonstrates the use of functions, visibility, and modifiers in a Solidity contract: + +``` +pragma solidity ^0.8.0; + +contract MyContract { + address public owner; + + constructor() { + owner = msg.sender; + } + + function myFunction(uint256 myParam) public onlyOwner { + // function code here + } + + function myInternalFunction() internal { + // function code here + } + + function myExternalFunction() external { + // function code here + } + + modifier onlyOwner() { + require(msg.sender == owner, "Only the contract owner can call this function."); + _; + } +} +``` + +In this example, we've defined a Solidity contract called `MyContract` that includes several different types of functions. We've defined a `myFunction()` function that can only be called by the owner of the contract, an `myInternalFunction()` function that can only be called from within the same contract, and an `myExternalFunction()` function that can be called from outside the contract. + +We've also defined a `onlyOwner()` modifier that ensures that certain functions can only be called by the owner of the contract. + +By using functions, visibility, and modifiers, we can create smart contracts that are both modular and secure, ensuring that functions are called only by authorized parties and that data is manipulated correctly and consistently. diff --git a/stepxx_web3/step05_solidity/step05_Solidity_Control_Structures/readme.md b/stepxx_web3/step05_solidity/step05_Solidity_Control_Structures/readme.md new file mode 100644 index 00000000..5655291a --- /dev/null +++ b/stepxx_web3/step05_solidity/step05_Solidity_Control_Structures/readme.md @@ -0,0 +1,81 @@ +## Solidity Control Structures + +Control structures in Solidity are used to control the flow of execution within a smart contract. They allow us to make decisions based on conditions and to repeat blocks of code multiple times. + +### If Statements + +If statements in Solidity allow us to make decisions based on conditions. They are declared using the `if` keyword, followed by a condition in parentheses and a block of code in curly braces. For example: + +``` +if (myVar == 42) { + // code to be executed if myVar is equal to 42 +} +``` + +We can also use `else` and `else if` statements to define additional conditions: + +``` +if (myVar == 42) { + // code to be executed if myVar is equal to 42 +} else if (myVar == 0) { + // code to be executed if myVar is equal to 0 +} else { + // code to be executed if myVar is not equal to 42 or 0 +} +``` + +### Loops + +Loops in Solidity allow us to repeat blocks of code multiple times. There are two main types of loops in Solidity: `for` loops and `while` loops. + +#### For Loops + +For loops in Solidity are declared using the `for` keyword, followed by an initialization statement, a condition, and an update statement, all separated by semicolons. The block of code to be executed is enclosed in curly braces. For example: + +``` +for (uint256 i = 0; i < 10; i++) { + // code to be executed 10 times +} +``` + +#### While Loops + +While loops in Solidity are declared using the `while` keyword, followed by a condition in parentheses and a block of code in curly braces. The block of code is executed repeatedly as long as the condition remains true. For example: + +``` +while (myVar < 10) { + // code to be executed as long as myVar is less than 10 +} +``` + +### Example + +Here's an example that demonstrates the use of control structures in a Solidity contract: + +``` +pragma solidity ^0.8.0; + +contract MyContract { + function myFunction(uint256 myVar) public pure returns (string memory) { + if (myVar == 42) { + return "The answer to life, the universe, and everything"; + } else if (myVar == 0) { + return "Zero is not allowed"; + } else { + uint256 i = 0; + while (i < myVar) { + i++; + } + return "Loop complete"; + } + } +} +``` + +In this example, we've defined a Solidity contract called `MyContract` that includes a function called `myFunction()` which takes a single input parameter `myVar`. + +Within `myFunction()`, we've used an `if` statement to check if `myVar` is equal to 42, and return a string if it is. We've also used an `else if` statement to check if `myVar` is equal to 0, and return a different string if it is. + +Finally, we've used a `while` loop to repeat a block of code `myVar` times if `myVar` is not equal to 42 or 0. This loop increments the variable `i` until it reaches the value of `myVar`, and then returns a string indicating that the loop is complete. + +By using control structures in our Solidity contracts, we can create smart contracts that make decisions based on conditions and repeat blocks of code diff --git a/stepxx_web3/step05_solidity/step06_Solidity_Events/readme.md b/stepxx_web3/step05_solidity/step06_Solidity_Events/readme.md new file mode 100644 index 00000000..541f312d --- /dev/null +++ b/stepxx_web3/step05_solidity/step06_Solidity_Events/readme.md @@ -0,0 +1,62 @@ +## Solidity Events + +Solidity events allow contracts to communicate with external applications by emitting notifications about specific contract events. Events are defined using the `event` keyword, and can be emitted using the `emit` keyword. + +### Declaring Events + +To declare an event in Solidity, we use the `event` keyword, followed by the name of the event and a list of parameters in parentheses. For example: + +``` +event NewUserRegistered(address userAddress, string username); +``` + +In this example, we've defined an event called `NewUserRegistered` that takes two parameters: an Ethereum address and a string representing the username of the registered user. + +### Emitting Events + +To emit an event in Solidity, we use the `emit` keyword followed by the name of the event and a list of arguments in parentheses. For example: + +``` +emit NewUserRegistered(msg.sender, "john_doe"); +``` + +In this example, we're emitting the `NewUserRegistered` event and passing in two arguments: the Ethereum address of the user who triggered the event (retrieved using `msg.sender`) and the username of the registered user. + +### Subscribing to Events + +External applications can subscribe to events emitted by a Solidity contract using the `event.watch()` function provided by web3.js. For example: + +``` +MyContract.NewUserRegistered(function(error, result) { + if (!error) { + console.log("New user registered: " + result.args.username); + } +}); +``` + +In this example, we're subscribing to the `NewUserRegistered` event emitted by a contract called `MyContract`. When the event is emitted, the `event.watch()` function is triggered and logs a message to the console with the username of the registered user. + +### Example + +Here's an example that demonstrates the use of events in a Solidity contract: + +``` +pragma solidity ^0.8.0; + +contract MyContract { + event NewUserRegistered(address userAddress, string username); + + function registerUser(string memory username) public { + // Register the user + emit NewUserRegistered(msg.sender, username); + } +} +``` + +In this example, we've defined a Solidity contract called `MyContract` that includes an event called `NewUserRegistered`. + +Within the contract, we've defined a function called `registerUser()` which takes a single input parameter `username`. When this function is called, it emits the `NewUserRegistered` event with the Ethereum address of the user who triggered the event (retrieved using `msg.sender`) and the username of the registered user. + +External applications can subscribe to this event using web3.js and receive notifications when a new user is registered. + +By using events in our Solidity contracts, we can create smart contracts that can communicate with external applications and notify them of specific contract events. diff --git a/stepxx_web3/step05_solidity/step07_Solidity_Inheritance/readme.md b/stepxx_web3/step05_solidity/step07_Solidity_Inheritance/readme.md new file mode 100644 index 00000000..1e11c02b --- /dev/null +++ b/stepxx_web3/step05_solidity/step07_Solidity_Inheritance/readme.md @@ -0,0 +1,126 @@ +## Solidity Inheritance + +Solidity supports the concept of inheritance, which allows a contract to inherit properties and functions from another contract. Inheritance is a powerful feature that can be used to create modular and extensible smart contracts. + +### Single Inheritance + +In Solidity, a contract can inherit from a single base contract using the `is` keyword. For example, consider the following contract: + +``` +pragma solidity ^0.8.0; + +contract Ownable { + address public owner; + + constructor() { + owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == owner, "Only the owner can call this function"); + _; + } +} + +contract MyContract is Ownable { + // Additional contract code +} +``` + +In this example, the `MyContract` contract inherits from the `Ownable` contract using the `is` keyword. This means that the `MyContract` contract will have access to the `owner` variable and `onlyOwner` modifier defined in the `Ownable` contract. + +### Multiple Inheritance + +Solidity also supports multiple inheritance, which allows a contract to inherit from multiple base contracts. To inherit from multiple base contracts, separate the base contracts with commas. For example: + +``` +pragma solidity ^0.8.0; + +contract A { + function foo() public pure returns (string memory) { + return "A"; + } +} + +contract B { + function foo() public pure returns (string memory) { + return "B"; + } +} + +contract C is A, B { + // Additional contract code +} +``` + +In this example, the `C` contract inherits from both the `A` and `B` contracts. If the `C` contract calls the `foo()` function, it will return the string "B", since the `B` contract is listed after the `A` contract in the inheritance hierarchy. + +### Overriding Inherited Functions + +Inherited functions can be overridden in the derived contract by defining a new function with the same name and signature. For example: + +``` +pragma solidity ^0.8.0; + +contract A { + function foo() public pure returns (string memory) { + return "A"; + } +} + +contract B is A { + function foo() public pure virtual returns (string memory) { + return "B"; + } +} + +contract C is B { + function foo() public pure override returns (string memory) { + return "C"; + } +} +``` + +In this example, the `B` contract overrides the `foo()` function defined in the `A` contract by defining a new function with the same name and signature. The `C` contract then overrides the `foo()` function defined in the `B` contract by defining a new function with the same name, signature, and the `override` keyword. + +### Example + +Here's an example that demonstrates the use of inheritance in Solidity: + +``` +pragma solidity ^0.8.0; + +contract Ownable { + address public owner; + + constructor() { + owner = msg.sender; + } + + modifier onlyOwner() { + require(msg.sender == owner, "Only the owner can call this function"); + _; + } +} + +contract Token { + mapping(address => uint256) public balances; + + function transfer(address to, uint256 amount) public { + balances[msg.sender] -= amount; + balances[to] += amount; + } +} + +contract MyToken is Token, Ownable { + string public name; + + constructor(string memory _name) { + name = _name; + } + + function mint(address to, uint256 amount) public onlyOwner { + balances[to] += amount; + } +} +``` diff --git a/stepxx_web3/step05_solidity/step08_Solidity_Libraries/readme.md b/stepxx_web3/step05_solidity/step08_Solidity_Libraries/readme.md new file mode 100644 index 00000000..78dde88c --- /dev/null +++ b/stepxx_web3/step05_solidity/step08_Solidity_Libraries/readme.md @@ -0,0 +1,47 @@ +## Solidity Libraries + +In Solidity, a library is a reusable piece of code that can be deployed independently and can be called by other contracts or libraries. Libraries are similar to contracts, but they cannot be deployed on their own and do not have their own storage. + +### Creating a Library + +To create a library in Solidity, you simply define a contract using the `library` keyword. The contract can contain functions that can be called by other contracts. Here is an example of a simple library that contains a function to calculate the factorial of a number: + +```solidity +library Math { + function factorial(uint256 n) public pure returns (uint256) { + if (n == 0) { + return 1; + } else { + return n * factorial(n - 1); + } + } +} +``` + +In this example, we have defined a library called `Math` that contains a single function called `factorial`. The function takes an unsigned integer `n` as an argument and returns its factorial. + +Note that we have declared the function as `public` and `pure`. `public` makes the function callable from other contracts, and `pure` indicates that the function does not read or modify the state of the contract. + +### Using a Library + +To use a library in another contract, you need to import it using the `import` statement. Here is an example of how to use the `Math` library we defined earlier: + +```solidity +pragma solidity ^0.8.0; + +import "./Math.sol"; + +contract MyContract { + function calculateFactorial(uint256 n) public pure returns (uint256) { + return Math.factorial(n); + } +} +``` + +In this example, we have imported the `Math` library using the `import` statement. We can then call the `factorial` function of the `Math` library in the `calculateFactorial` function of our contract. + +Note that we have used the dot notation to call the `factorial` function of the `Math` library. + +### Deploying a Library + +To deploy a library, you simply compile and deploy the contract as you would with any other contract. However, since libraries cannot be deployed on their own, you will need to include them in another contract that calls the library functions. diff --git a/stepxx_web3/step05_solidity/step09_Solidity_Testing/readme.md b/stepxx_web3/step05_solidity/step09_Solidity_Testing/readme.md new file mode 100644 index 00000000..aba3965a --- /dev/null +++ b/stepxx_web3/step05_solidity/step09_Solidity_Testing/readme.md @@ -0,0 +1,45 @@ +## Solidity Testing + +Testing is an important aspect of software development, and Solidity is no exception. Solidity provides a built-in testing framework that allows you to write tests to verify the correctness of your contracts. + +### Testing Framework + +Solidity's testing framework is based on the popular testing framework Mocha. To use the Solidity testing framework, you will need to install Mocha and the Solidity plugin. You can do this using the following commands: + +``` +npm install --save-dev mocha +npm install --save-dev @ethereum-waffle/chai +npm install --save-dev @nomiclabs/hardhat-ethers ethers +``` + +Once you have installed these packages, you can create a test file in the `test` directory of your project. + +### Writing Tests + +To write tests, you simply define a function using the `it` keyword. The function should contain the test code that you want to run. Here is an example of a simple test that verifies the functionality of a contract: + +``` +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "chai/register-expect"; +import { ethers } from "hardhat"; +import { MyContract } from "../artifacts/contracts/MyContract.sol/MyContract.json"; + +describe("MyContract", function () { + it("should return the correct value", async function () { + const MyContractFactory = await ethers.getContractFactory("MyContract"); + const myContract = await MyContractFactory.deploy(); + await myContract.deployed(); + + const result = await myContract.myFunction(); + expect(result).to.equal("Hello, World!"); + }); +}); +``` + +In this example, we have defined a test function using the `it` keyword. The test function creates an instance of the `MyContract` contract using the `MyContractFactory` and calls the `myFunction` function. The test function then verifies that the function returns the correct value using the `expect` assertion. + +### Running Tests + +To run tests, you simply use the `npx hardhat test` command. This will run all the tests in the `test` directory of your project. diff --git a/stepxx_web3/step05_solidity/step10_Solidity_Deployment/readme.md b/stepxx_web3/step05_solidity/step10_Solidity_Deployment/readme.md new file mode 100644 index 00000000..3a3afa91 --- /dev/null +++ b/stepxx_web3/step05_solidity/step10_Solidity_Deployment/readme.md @@ -0,0 +1,65 @@ +## Solidity Deployment + +After writing and testing your Solidity smart contracts, the next step is to deploy them to the blockchain. In this README, we will go over the steps to deploy your Solidity smart contracts. + +### Deployment Steps + +1. Compile your contracts - Before you can deploy your contracts, you need to compile them into bytecode that can be executed on the blockchain. You can use Solidity's built-in compiler or a third-party tool like Truffle to compile your contracts. + +2. Choose your deployment method - There are several methods you can use to deploy your contracts, including: + + - Using the Remix IDE - Remix is a browser-based IDE that allows you to deploy your contracts directly from the IDE. + + - Using a deployment tool like Truffle - Truffle is a popular development framework that includes a deployment tool that allows you to easily deploy your contracts to the blockchain. + + - Using a deployment script - You can write a deployment script that uses a library like Web3.js to deploy your contracts to the blockchain. + +3. Choose your network - You need to choose the network you want to deploy your contracts to. This could be a test network like Rinkeby or Ropsten, or it could be the main Ethereum network. + +4. Deploy your contracts - Once you have compiled your contracts, chosen your deployment method, and chosen your network, you are ready to deploy your contracts. Follow the steps for your chosen deployment method to deploy your contracts to the blockchain. + +### Example Deployment Script + +Here is an example deployment script that uses Web3.js to deploy a contract to the Rinkeby test network: + +``` +const Web3 = require("web3"); +const fs = require("fs"); +const solc = require("solc"); + +// Connect to the Rinkeby network +const web3 = new Web3( + new Web3.providers.HttpProvider( + "https://rinkeby.infura.io/v3/INFURA_PROJECT_ID" + ) +); + +// Compile the contract +const input = fs.readFileSync("MyContract.sol", "utf8"); +const output = solc.compile(input, 1); +const bytecode = output.contracts[":MyContract"].bytecode; +const abi = JSON.parse(output.contracts[":MyContract"].interface); + +// Create a new contract object +const MyContract = new web3.eth.Contract(abi); + +// Deploy the contract +MyContract.deploy({ + data: bytecode, + arguments: ["Hello, World!"], +}) + .send({ + from: "0xYourAddress", + gas: 1500000, + gasPrice: "30000000000", + }) + .then((contract) => { + console.log("Contract deployed at address:", contract.options.address); + }); +``` + +In this example, we are deploying a contract to the Rinkeby test network using a deployment script that uses Web3.js. We first compile the contract using the `solc` library and create a new contract object using the ABI. We then deploy the contract using the `send` function and specify the contract bytecode, arguments, gas, gas price, and from address. + +## Conclusion + +Deploying Solidity smart contracts can be a complex process, but by following the steps outlined in this README and using the appropriate tools and libraries, you can easily deploy your contracts to the blockchain. From cfad98ceeded29df73204a843e8db279c7c662f9 Mon Sep 17 00:00:00 2001 From: Asharib Ali Date: Tue, 2 May 2023 21:35:34 +0500 Subject: [PATCH 2/2] learn hardhat in baby steps --- .../step00_hardhat_in_baby_steps/readme.md | 104 ++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 stepxx_web3/step04_hardhat/step00_hardhat_in_baby_steps/readme.md diff --git a/stepxx_web3/step04_hardhat/step00_hardhat_in_baby_steps/readme.md b/stepxx_web3/step04_hardhat/step00_hardhat_in_baby_steps/readme.md new file mode 100644 index 00000000..9db9c0ef --- /dev/null +++ b/stepxx_web3/step04_hardhat/step00_hardhat_in_baby_steps/readme.md @@ -0,0 +1,104 @@ +# Hardhat: A Comprehensive Development Environment for Ethereum + +Hardhat is a development environment for Ethereum that provides a wide range of tools and features to help you build, test, and deploy smart contracts. It is designed to be flexible and extensible, with a plugin system that allows you to customize your workflow and integrate with other tools and services. + +## Key Features + +Some of the key features of Hardhat include: + +- **Solidity Compiler:** Hardhat includes the Solidity compiler, which allows you to compile your smart contracts and generate the necessary bytecode and ABI files. + +- **Automated Testing:** Hardhat provides a testing framework based on Mocha and Chai, making it easy to write and run automated tests for your smart contracts. + +- **Contract Deployment:** Hardhat allows you to deploy your smart contracts to a variety of Ethereum networks, including local networks, testnets, and mainnet. + +- **Debugging and Tracing:** Hardhat includes a built-in debugger and tracing tool, which makes it easy to diagnose issues and errors in your smart contract code. + +- **Ethereum Network Management:** Hardhat includes support for a variety of Ethereum networks, and makes it easy to manage and switch between them. + +## Step 1: Setting Up Your Hardhat Environment + +To get started with Hardhat, you will need to have Node.js installed on your computer. Once you have Node.js installed, you can use npm to install Hardhat globally by running the following command in your terminal: + +``` +npm install -g hardhat +``` + +Once Hardhat is installed, you can create a new project by running the following command: + +``` +npx hardhat +``` + +This will create a new Hardhat project with some default settings. You can then navigate to your new project directory and start exploring the code. + +## Step 2: Understanding the Hardhat Project Structure + +When you create a new Hardhat project, it will generate a number of files and directories. Here is a brief overview of some of the most important files and directories: + +- `contracts/`: This directory contains your Solidity smart contracts. +- `test/`: This directory contains your automated tests. +- `scripts/`: This directory contains any custom scripts you want to run in your Hardhat environment. +- `hardhat.config.js`: This is the configuration file for your Hardhat project. You can use this file to configure your network settings, plugins, and other project-specific settings. + +## Running Commands + +Hardhat provides a number of command-line tools and utilities that you can use to build, test, and deploy your smart contracts. Here are a few of the most common commands: + +- `npx hardhat compile`: Compiles your Solidity contracts and generates the necessary bytecode and ABI files. +- `npx hardhat test`: Runs your automated tests and reports any failures. +- `npx hardhat run scripts/deploy.js --network NETWORK_NAME`: Deploys your contracts to the specified network. + +## Step 3: Compiling Your Smart Contracts + +Once you have created your Hardhat project and written your Solidity smart contracts, you can use Hardhat to compile your code by running the following command: + +``` +npx hardhat compile +``` + +This will compile all of your Solidity contracts and generate the necessary bytecode and ABI files. + +## Step 4: Running Automated Tests + +Hardhat makes it easy to write and run automated tests for your Solidity contracts. You can write your tests using the Mocha testing framework and the Chai assertion library. Here is an example test script: + +```javascript +const { expect } = require("chai"); + +describe("MyContract", function () { + it("should return the correct name", async function () { + const MyContract = await ethers.getContractFactory("MyContract"); + const contract = await MyContract.deploy(); + await contract.deployed(); + + expect(await contract.name()).to.equal("MyContract"); + }); +}); +``` + +To run your tests, you can use the following command: + +``` +npx hardhat test +``` + +This will run all of your tests and report any failures. + +## Step 5: Deploying Your Contracts + +Once you have written and tested your Solidity contracts, you can use Hardhat to deploy them to a blockchain network. Hardhat supports a number of different networks, including Ethereum, Binance Smart Chain, and others. + +To deploy your contracts, you will need to update your `hardhat.config.js` file with the appropriate network settings. You can then use the following command to deploy your contracts: + +``` +npx hardhat run scripts/deploy.js --network NETWORK_NAME +``` + +This will deploy your contracts to the specified network. You can then interact with your contracts using a tool like Remix or web3.js. + +These are just a few of the basics of working with Hardhat. There is much more to learn about this powerful development framework, but hopefully these steps will give you a good starting point. + +## Conclusion + +Hardhat is a powerful and flexible development environment for Ethereum that provides a wide range of tools and features to help you build, test, and deploy smart contracts. Whether you are a seasoned developer or just getting started with Ethereum development, Hardhat is an essential tool that can help you streamline your workflow and build more robust and reliable smart contracts.