Repository: nehal2210/Blockchain-Engineer-Course Branch: main Commit: 8cbebbe33c01 Files: 37 Total size: 37.1 KB Directory structure: gitextract_o_x7fhhy/ ├── Coin vs Theory.pptx ├── EtherJS/ │ ├── index.js │ └── package.json ├── README.md └── SmartContracts/ ├── 1_Storage.sol ├── AccessModifier.sol ├── Array.sol ├── Constant.sol ├── Constructors.sol ├── DataLocations.sol ├── EncodeDecode.sol ├── Enum.sol ├── Errors.sol ├── EtherUnits.sol ├── Events.sol ├── FunctionModifier.sol ├── Functions.sol ├── Gas.sol ├── GasOpt.sol ├── GlobalVariables.sol ├── HelloWorld.sol ├── IfElse.sol ├── Immutable.sol ├── Import.sol ├── Inharitance.sol ├── LocalVariables.sol ├── Loops.sol ├── Mappings.sol ├── MathLib.sol ├── Payable.sol ├── SendEther.sol ├── SimpleStorage.sol ├── StateVariable.sol ├── Struct.sol ├── UseMathLib.sol ├── Variables.sol └── ViewPure.sol ================================================ FILE CONTENTS ================================================ ================================================ FILE: EtherJS/index.js ================================================ const ethers = require("ethers"); const dotenv = require("dotenv"); dotenv.config(); async function main() { const provider = new ethers.providers.JsonRpcProvider( "RPC_PROVIDER_URL" ); // provider // console.log(await provider.getBlockNumber()); // const bal = await provider.getBalance( // "0xbcFA8eAB1fCe576F1Ef71772E46519e0ADC06623" // ); // console.log(ethers.utils.formatEther(bal)); // console.log(await provider.getBlock()); // signer // console.log(); const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider); // let tx = { // to: "0xbcFA8eAB1fCe576F1Ef71772E46519e0ADC06623", // value: ethers.utils.parseEther("0.01"), // }; // // 2.22 // let TX = await signer.sendTransaction(tx); // await TX.wait(); // console.log(TX); // contract const contract_address = "0x35595cc6DD5CF938c24f393b6F7282109253C84A"; const ABI = [ { inputs: [], stateMutability: "nonpayable", type: "constructor", }, { inputs: [ { internalType: "address", name: "addr", type: "address", }, ], name: "NotAnOwner", type: "error", }, { inputs: [ { internalType: "uint256", name: "_id", type: "uint256", }, ], name: "TaskNotCompleted", type: "error", }, { inputs: [ { internalType: "uint256", name: "_id", type: "uint256", }, ], name: "TaskNotExist", type: "error", }, { anonymous: false, inputs: [ { indexed: false, internalType: "uint256", name: "reward", type: "uint256", }, ], name: "TaskComplete", type: "event", }, { anonymous: false, inputs: [ { indexed: false, internalType: "uint256", name: "id", type: "uint256", }, { indexed: false, internalType: "string", name: "work", type: "string", }, { indexed: false, internalType: "bool", name: "status", type: "bool", }, ], name: "TaskCreated", type: "event", }, { anonymous: false, inputs: [ { indexed: false, internalType: "uint256", name: "id", type: "uint256", }, { indexed: false, internalType: "string", name: "work", type: "string", }, { indexed: false, internalType: "bool", name: "status", type: "bool", }, ], name: "TaskStatusChange", type: "event", }, { stateMutability: "payable", type: "fallback", }, { inputs: [], name: "TodosCompleted", outputs: [], stateMutability: "payable", type: "function", }, { inputs: [ { internalType: "string", name: "_work", type: "string", }, ], name: "createTask", outputs: [], stateMutability: "payable", type: "function", }, { inputs: [], name: "getBalance", outputs: [ { internalType: "uint256", name: "", type: "uint256", }, ], stateMutability: "view", type: "function", }, { inputs: [], name: "getRevenue", outputs: [ { internalType: "uint256", name: "", type: "uint256", }, ], stateMutability: "view", type: "function", }, { inputs: [], name: "getReward", outputs: [ { internalType: "uint256", name: "", type: "uint256", }, ], stateMutability: "view", type: "function", }, { inputs: [], name: "getTasks", outputs: [ { components: [ { internalType: "string", name: "work", type: "string", }, { internalType: "bool", name: "status", type: "bool", }, ], internalType: "struct ToDo.task[]", name: "", type: "tuple[]", }, ], stateMutability: "view", type: "function", }, { inputs: [ { internalType: "address", name: "_owner", type: "address", }, ], name: "setOwner", outputs: [], stateMutability: "nonpayable", type: "function", }, { inputs: [ { internalType: "uint256", name: "_id", type: "uint256", }, ], name: "toggleTask", outputs: [], stateMutability: "nonpayable", type: "function", }, { inputs: [], name: "withDraw", outputs: [], stateMutability: "nonpayable", type: "function", }, { stateMutability: "payable", type: "receive", }, ]; const contract = new ethers.Contract(contract_address, ABI, signer); // const creatTask_tx = await contract.createTask("clean the window", { // value: ethers.utils.parseEther("0.1"), // }); // await creatTask_tx.wait(); // console.log(creatTask_tx); // const toggleTask_tx = await contract.toggleTask(0); // await toggleTask_tx.wait(); // console.log(toggleTask_tx); // console.log(await contract.getTasks()); // console.log(ethers.utils.formatEther(await contract.getReward())); const TodosCompleted_tx = await contract.TodosCompleted(); await TodosCompleted_tx.wait(); console.log(TodosCompleted_tx); } main(); ================================================ FILE: EtherJS/package.json ================================================ { "name": "ethjs-tutorial", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "dotenv": "^16.0.3", "ethers": "^5.7.2" } } ================================================ FILE: README.md ================================================ # Blockchain-Engineer-Course ## MODULE : 1 Introduction to Blockchain 1. Introduction to Course https://youtu.be/t0Bb7Tl6bw4 2. How to get Most out from this Course https://youtu.be/g4sF_PCgXT4 3. What is Blockchain https://youtu.be/v40mFP6BR3I 4. How Blockchain Works https://youtu.be/3WUHewOsABk * Proof of Work Demo https://andersbrownworth.com/blockchain/hash * How people of Yapis use Blockchain https://www.youtube.com/watch?v=oNhpm9NMVXs&t=1s * How Proof of Stack Works https://www.youtube.com/watch?v=M3EFi_POhps 5. Why Web3 | Perpouse of Smart Contracts https://youtu.be/J_Lyx4fx4Nw * Vitalik Buterin https://vitalik.ca/ * Satoshi White Paper https://github.com/nehal2210/Blockchain-Engineer-Course/blob/main/Satoshi%20white%20paper.pdf * Ethereum White paper https://ethereum.org/en/whitepaper/ * Ethereum Yellow Paper https://github.com/nehal2210/Blockchain-Engineer-Course/blob/main/ethereum%20yello%20paper.pdf ## MODULE : 2 Development of Smart Contracts * Smart Contracts https://github.com/nehal2210/Blockchain-Engineer-Course/tree/main/SmartContracts * Smart Contract By Example https://solidity-by-example.org/ ## MODULE : 3 Dapps * Ether JS https://github.com/nehal2210/Blockchain-Engineer-Course/tree/main/EtherJS * Decentalize Todo List https://github.com/nehal2210/D-Todo * Assignment Smart Contract Lottery https://youtu.be/aFI_XPll_mg * Token Vendor Machine https://github.com/nehal2210/Token-Vendor-Machine * Base64 Encoding https://www.youtube.com/watch?v=wdeZIOJjjdE ## MODULE : 6 Applications (PARALLEL MODULE) * Coin VS Toke By Muhammad Nouman https://github.com/nehal2210/Blockchain-Engineer-Course/blob/main/Coin%20vs%20Theory.pptx ## Learning Resources * Speed Run Ethereum https://speedrunethereum.com/ * BuildSpace https://buildspace.so/p/mint-nft-collection * Patrick Collins https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=7238s * Chainlink Services Overview By Hari https://youtu.be/nHn7u9wSHZs?list=PLVP9aGDn-X0Q1L67bV_AbDd75qTY6Ylxw ## GitHub * How to create PR https://firstcontributions.github.io/ * How to create Github Issues https://www.youtube.com/watch?v=TJlYiMp8FuY **Note: PR Format branch name your-name/feature-you have change/add** **e.g. nehal/module2-doc** # Assignment * https://github.com/nehal2210/Blockchain-Engineer-Course/blob/main/BLockchain%20Engineer%20Course%20Assignment.pdf # Submitted Assignmets By Blockchain Ninjas * FullName (url) ## OUR COLLABORATORS
| Haseeb Ahmed | Nehal Ahmed | Muhammad Nouman | |:---:|:---:|:---:| | Haseeb Ahmed | Nehal Ahmed | Muhammad Nouman |
================================================ FILE: SmartContracts/1_Storage.sol ================================================ // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; /** * @title Storage * @dev Store & retrieve value in a variable * @custom:dev-run-script ./scripts/deploy_with_ethers.ts */ contract Storage { uint256 number; /** * @dev Store value in variable * @param num value to store */ function store(uint256 num) public { number = num; } /** * @dev Return value * @return value of 'number' */ function retrieve() public view returns (uint256){ return number; } } ================================================ FILE: SmartContracts/AccessModifier.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Access Modifiers: scope accessiblity // internal : can access only inside the contract and derive contract // external : can access only from outside of contract // public : can access from every where // private : can access only inside the contract // By default variables are internal // only use in state variables and functions // external can only be used with functions contract A{ uint internal a = 5; function access() external view returns(uint){ return a; } // function accessExternal() public view returns(uint){ // return access(); // } } contract B is A{ uint public b = a; } ================================================ FILE: SmartContracts/Array.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // Array // Array can have a compile-time fixed size or a dynamic size. // get ,add, update, delete // Compile-time : when we write code // Run-time : when code is running contract Array { // Several ways to initialize an array uint[] public arr; uint[] public arr2 = [1, 2, 3]; // Fixed sized array, all elements initialize to 0 uint[10] public myFixedSizeArr;//[0,0,0,0,0,0,0..] function get(uint i) public view returns (uint) { return arr[i]; } // Solidity can return the entire array. // But this function should be avoided for // arrays that can grow indefinitely in length. function getArr() public view returns (uint[] memory) { return arr; } function push(uint i) public { // Append to array // This will increase the array length by 1. arr.push(i);//[1,2,3,10] } function pop() public { // Remove last element from array // This will decrease the array length by 1 arr.pop(); } function getLength() public view returns (uint) { return arr.length; } function remove(uint index) public { // Delete does not change the array length. // It resets the value at index to it's default value, // in this case 0 delete arr[index]; } function examples() pure external { // create array in memory, only fixed size can be created uint[] memory b = new uint[](5); } } ================================================ FILE: SmartContracts/Constant.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // contsant variable values never change; // they must be initialize before the deployment of contract // it saves gas cost contract Constant{ // 23471 gas uint256 public vari_num = 10; //21393 gas uint256 public constant MY_NUM = 10; } ================================================ FILE: SmartContracts/Constructors.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // A constructor is an optional function that is executed upon contract creation. // Here are examples of how to pass arguments to constructors. // Base contract X contract X { string public name; constructor(string memory _name) { name = _name; } } // // Base contract Y contract Y { string public text; constructor(string memory _text) { text = _text; } } contract C is X, Y { // Pass the parameters here in the constructor, // similar to function modifiers. constructor(string memory _name, string memory _text) X(_name) Y(_text) {} } // // Parent constructors are always called in the order of inheritance // // regardless of the order of parent contracts listed in the // // constructor of the child contract. // // Order of constructors called: // // 1. X // // 2. Y // // 3. D contract D is X, Y { constructor() X("X was called") Y("Y was called") {} } ================================================ FILE: SmartContracts/DataLocations.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // Variables are declared as either storage, memory or calldata to explicitly specify the location of the data. // mostly use explicitly in bytes,string, array and mapping,struct // storage - variable is a state variable (store on blockchain) // memory - variable is in memory and it exists while a function is being called,However, they are mutable within that function. // calldata - Calldata is an immutable, temporary location where function arguments are stored, and behaves mostly like memory. // special data location that contains function arguments contract DataLocation{ struct Todo { string text; bool completed; } // An array of 'Todo' structs Todo[] public todos; function create(string calldata _text) public { todos.push(Todo(_text, false)); } // Solidity automatically created a getter for 'todos' so // you don't actually need this function. function get(uint _index) public view returns (string memory text, bool completed) { Todo storage todo = todos[_index]; return (todo.text, todo.completed); } // update text function updateText(uint _index, string calldata _text) public { Todo storage todo = todos[_index]; todo.text = _text; } } ================================================ FILE: SmartContracts/EncodeDecode.sol ================================================ pragma solidity 0.8.7; // abi.encode encodes data into bytes. // abi.decode decodes bytes back into data. contract EncodeDecode{ function encode(uint x,address addr) external pure returns (bytes memory) { return abi.encode(x, addr); } function decode(bytes calldata data) external pure returns (uint n, address adr) { (n,adr) =abi.decode(data,(uint,address)); } function hash( uint num, address addr ) public pure returns (bytes32) { return keccak256(abi.encode(num, addr)); } function verifyHash( uint num, address addr, bytes32 _hash ) public pure returns (bool) { return keccak256(abi.encode(num, addr)) == _hash; } } ================================================ FILE: SmartContracts/Enum.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // Enum // Solidity supports enumerables and they are useful to model choice and keep track of state. // Enums can be declared outside of a contract. // enums are also called custom data type contract Enum { // Enum representing shipping status enum Status { Pending, Shipped, Accepted, Rejected, Canceled } // Default value is the first element listed in // definition of the type, in this case "Pending" Status public status; // Status public status = Status.Pending; // Returns uint // Pending - 0 // Shipped - 1 // Accepted - 2 // Rejected - 3 // Canceled - 4 function get() public view returns (Status) { // status = Status.Shipped; return status; } // Update status by passing uint into input function set(Status _status) public { // require(_status==Status.Pending,"error"); status = _status; } // You can update to a specific enum like this function cancel() public { status = Status.Canceled; } // delete resets the enum to its first value, 0 function reset() public { delete status; } } ================================================ FILE: SmartContracts/Errors.sol ================================================ // Error // An error will undo all changes made to the state during a transaction. // You can throw an error by calling require, revert or assert. // require is used to validate inputs and conditions before execution. // revert is similar to require. See the code below for details. // assert is used to check for code that should never be false. Failing assertion probably means that there is a bug. // Use custom error to save gas. // SPDX-License-Identifier: MIT // Proposed Solidity best practice: // Use the name of the smart contract as a prefix for custom errors. // This helps end users identify which contract reverted a failed tx, which is especially useful for complex txs that involve multiple contracts. pragma solidity ^0.8.7; contract Error { error Error__GreaterThanTen(uint amount); function testRequire(uint _i) public pure returns(uint) { // Require should be used to validate conditions such as: // - inputs // - conditions before execution // - return values from calls to other functions require(_i > 10, "Input must be greater than 10"); return _i; } function testRevert(uint _i) public pure returns(uint) { // Revert is useful when the condition to check is complex. // This code does the exact same thing as the example above if (_i <= 10) { revert Error__GreaterThanTen({amount:_i}); } return _i; } } ================================================ FILE: SmartContracts/EtherUnits.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Ether and Wei // Transactions are paid with ether. // Similar to how one dollar is equal to 100 cent, one ether is equal to 10^18 wei. contract EtherUnits { // uint n = 1; uint public oneWei = 1 wei; // 1 wei is equal to 1 bool public isOneWei = 1 wei == 1; uint public oneEther = 1 ether; // 1 ether is equal to 10^18 wei bool public isOneEther = 1 ether == 1e18; } ================================================ FILE: SmartContracts/Events.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // Events allow logging to the Ethereum blockchain. Some use cases for events are: // Listening for events and updating user interface // A cheap form of storage contract Event { // Event declaration // Up to 3 parameters can be indexed. // Indexed parameters helps you filter the logs by the indexed parameter event Log(address indexed sender, string message); event AnotherLog(); function test() public { emit Log(msg.sender, "Hello World!"); emit Log(msg.sender, "Hello EVM!"); emit AnotherLog(); } } ================================================ FILE: SmartContracts/FunctionModifier.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Function Modifier // Modifiers can be used to: // Restrict access // Validate inputs // Guard against reentrancy hack // modifier is used to reuse the code, // it can be used by three ways // without argument // with argument // sandwhich contract FunctionModifier{ address public owner = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4; modifier onlyOwner(){ require(msg.sender==owner,"you are not an owner"); _; //jis function se aae ho us function me jaao } modifier validateNumber(uint num){ require(num==10,"not 10"); _; //jis function se aae ho us function me jaao } function secret(uint num) external view onlyOwner validateNumber(num) returns(address){ return owner; } } ================================================ FILE: SmartContracts/Functions.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Function: // A piece of code which may or may not take some input, do some coputation and return output // Once a function is defined, it can be used over and over and over again // In solidity there are many ways to write function in terms of output. // 1. return single value // 2. return multiple values // 3. return multiple values without return statement(by declaring return values in the definition of function) // Use destructuring assignment when calling another // function that returns multiple values. contract Functions{ uint public x = 5; function SingleValue(uint num) public view returns(uint){ return num + x; } function useSingleValue() public view returns(uint){ uint y = SingleValue(8); return y; } function MultipleValues()public pure returns(uint,bool,int){ uint u =5; bool y = true; int z = 10; // return (5,true,10) return (u,y,z); } function MultipleValuesDec()public pure returns(uint u,bool y,int z){ u = 5; y = true; // z = 10; // return (5,true,10) // return (u,y,z); } function Destructuring() public pure returns(uint){ (uint a, uint b,uint c) = (5,6,7); return a+b+c; } function useMultibleValues() public pure returns(uint,bool,int){ (uint a,bool b,int c) = MultipleValues(); return (a,b,c); } } ================================================ FILE: SmartContracts/Gas.sol ================================================ // Gas // How much ether do you need to pay for a transaction? // You pay gas spent * gas price amount of ether, where // gas is a unit of computation // gas spent is the total amount of gas used in a transaction // gas price is how much ether you are willing to pay per gas // Transactions with higher gas price have higher priority to be included in a block. // Unspent gas will be refunded. // Gas Limit // There are 2 upper bounds to the amount of gas you can spend // gas limit (max amount of gas you're willing to use for your transaction, set by you) // block gas limit (max amount of gas allowed in a block, set by the network) ================================================ FILE: SmartContracts/GasOpt.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; contract GasOpt { // start - 50992 gas // use calldata - 49163 gas // load state variables to memory - 48952 gas // short circuit - 48634 gas // loop increments - 48244 gas // cache array length - 48201 gas // load array elements to memory - 48039 gas // uncheck i overflow/underflow - 47301 gas uint public total; // [1, 2, 3, 4, 5, 100] function sumIfEvenAndLessThan99(uint[] calldata nums) external { uint _total; uint l = nums.length; for (uint i = 0; i < l;) { uint n = nums[i]; if (n % 2 == 0 && n < 99) { _total += n; } unchecked{ ++i; } } total = _total; } } ================================================ FILE: SmartContracts/GlobalVariables.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Global Variables − // Special variables exists in the global namespace used to get information about the blockchain. // e.g. // block.chainid (uint): current chain id // block.difficulty (uint): current block difficulty // block.number (uint): current block number // c (uint): current block timestamp as seconds since unix epoch // msg.data (bytes calldata): complete calldata // msg.sender (address): sender of the message (current call) // msg.sig (bytes4): first four bytes of the calldata (i.e. function identifier) // msg.value (uint): number of wei sent with the message contract GlobalVariables{ function global() external view returns(address,uint,uint){ address sender = msg.sender; uint blockNum = block.number; uint blockDiff = block.difficulty; return(sender,blockNum,blockDiff); } } ================================================ FILE: SmartContracts/HelloWorld.sol ================================================ // SPDX-License-Identifier: MIT // pragma solidity >0.8.0 < 0.9.9 // pragma solidity ^0.8.0; pragma solidity 0.8.7; contract HelloWorld{ string public greet = "Hello World"; } ================================================ FILE: SmartContracts/IfElse.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Operators // == equal to // < less than // > greater than // <= less than equal to // >= greater than equal to // != not equals to // Logical Operators: // AND (cond1 && cond2) True when both conditions are true // OR (cond1 || cond2) True when any one condition is true // require(condition,"error msg") // if true continue execution otherwise print return error msg and stop excecution contract IfElse{ function grade(uint num) external pure returns(uint){ require(num>10,"num is less than 10"); return num; } function gradeIfElse(uint num) external pure returns(uint){ if(num > 10){ return 90; } else{ return 70; } } function ternary(uint num) external pure returns(uint){ // condition ? when true : when false return num>10 ? 90 : 70; } } ================================================ FILE: SmartContracts/Immutable.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; contract Immutable{ uint public constant MY_NUM = 10; address public immutable IMM_OWNER; // contsant variable values never change; // they must be initialize during the deployment of contract // it saves gas cost constructor (address _owner){ IMM_OWNER = _owner; } } ================================================ FILE: SmartContracts/Import.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./HelloWorld.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.5/contracts/token/ERC20/ERC20.sol"; contract IMport is ERC20 { // HelloWorld h = new HelloWorld(); // string public hello = h.greet(); constructor(string memory name_, string memory symbol_) ERC20(name_,symbol_) {} } ================================================ FILE: SmartContracts/Inharitance.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Solidity supports multiple inheritance. Contracts can inherit other contract by using the "is" keyword. // Function that is going to be overridden by a child contract must be declared as virtual. // Function that is going to override a parent function must use the keyword override. // Order of inheritance is important. // H.W : What is Multiple Inharitace and Multilevel Inharitance contract A { function foo() public pure virtual returns (string memory) { return "A"; } } // Contracts inherit other contracts by using the keyword 'is'. contract B is A { // Override A.foo() function foo() public pure virtual override returns (string memory) { return "B"; } } contract C is B { // Override A.foo() function foo() public pure override returns (string memory) { return "C"; } } ================================================ FILE: SmartContracts/LocalVariables.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Local Variable // Variables whose values are available only within a function where it is defined. // Function parameters are always local to that function. // Always declare or initilaize inside a function contract LocalVariables{ uint public num; //state Variable // write function setNum(uint number) external{ num = number; } function add(uint _a, uint _b ) external pure returns(uint){ // local variabels uint a =_a; uint b = _b; return a+b; } } ================================================ FILE: SmartContracts/Loops.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // For and While Loop // Solidity supports for, while, and do while loops. // Don't write loops that are unbounded as this can hit the gas limit, causing your transaction to fail. // For the reason above, while and do while loops are rarely used. contract Loops{ function Forloop() public pure returns(uint) { // for loop // i++ => i = i + 1 uint c = 0; for (uint i = 0; i < 10; i++) { if (i == 3) { // Skip to next iteration with continue continue; } if (i == 5) { // Exit loop with break break; } c+=1; // c = 4 } return c; } function Whileloop() public pure returns(uint) { // while loop uint j;//0 while (true) { j++;//j = j + 1 } return j; } } ================================================ FILE: SmartContracts/Mappings.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Mapping // Maps are created with the syntax mapping(keyType => valueType). // The keyType can be any built-in value type, bytes, string, or any contract. // valueType can be any type including another mapping or an array. // Mappings are not iterable. contract Mapping{ // Mapping from address to uint mapping(address => uint) public myMap; function get(address _addr) public view returns (uint) { // Mapping always returns a value. // If the value was never set, it will return the default value. return myMap[_addr]; } function set(address _addr, uint _i) public { // Update the value at this address myMap[_addr] = _i; } function remove(address _addr) public { // Reset the value to the default value. delete myMap[_addr]; } } contract NestedMapping { // Nested mapping (mapping from address to another mapping) mapping(address => mapping(uint => bool)) public nested; function get(address _addr1, uint _i) public view returns (bool) { // You can get values from a nested mapping // even when it is not initialized return nested[_addr1][_i]; } function set( address _addr1, uint _i, bool _boo ) public { nested[_addr1][_i] = _boo; } function remove(address _addr1, uint _i) public { delete nested[_addr1][_i]; } } ================================================ FILE: SmartContracts/MathLib.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // Library // Libraries are similar to contracts, but you can't declare any state variable and you can't send ether. // A library is embedded into the contract if all library functions are internal. // Otherwise the library must be deployed and then linked before the contract is deployed. library Math{ function add(uint a, uint b) internal pure returns(uint){ return a+b; } } ================================================ FILE: SmartContracts/Payable.sol ================================================ // Payable // Functions and addresses declared payable can receive ether into the // contract. // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; contract Payable { // Payable address can receive Ether address payable public owner; // Payable constructor can receive Ether constructor() payable { owner = payable(msg.sender); } // Function to deposit Ether into this contract. // Call this function along with some Ether. // The balance of this contract will be automatically updated. function deposit() public payable {} // Call this function along with some Ether. // The function will throw an error since this function is not payable. function notPayable() public {} // Function to withdraw all Ether from this contract. function getBalance() public view returns(uint) { // get the amount of Ether stored in this contract uint amount = address(this).balance; return amount; } } ================================================ FILE: SmartContracts/SendEther.sol ================================================ // How to send Ether? // You can send Ether to other contracts by // transfer (2300 gas, throws error) // send (2300 gas, returns bool) // call (forward all gas or set gas, returns bool) // How to receive Ether? // A contract receiving Ether must have at least one of the functions below // receive() external payable // fallback() external payable // receive() is called if msg.data is empty, otherwise fallback() is called. // Which method should you use? // call in combination with re-entrancy guard is the recommended method to use after December 2019. // SPDX-License-Identifier: MIT pragma solidity 0.8.7; contract ReceiveEther { /* Which function is called, fallback() or receive()? send Ether | msg.data is empty? / \ yes no / \ receive() exists? fallback() / \ yes no / \ receive() fallback() */ // 0x5e17b14ADd6c386305A32928F985b29bbA34Eff5 // Function to receive Ether. msg.data must be empty receive() external payable { } // Fallback function is called when msg.data is not empty fallback() external payable {} function getBalance() public view returns (uint) { return address(this).balance; } } contract SendEther { function sendViaTransfer(address payable _to) public payable { // This function is no longer recommended for sending Ether. _to.transfer(msg.value); } function sendViaSend(address payable _to) public payable { // Send returns a boolean value indicating success or failure. // This function is not recommended for sending Ether. bool sent = _to.send(msg.value); require(sent, "Failed to send Ether"); } function sendViaCall(address payable _to) public payable { // Call returns a boolean value indicating success or failure. // This is the current recommended method to use. (bool sent, bytes memory data) = _to.call{value: msg.value}(""); require(sent, "Failed to send Ether"); } } ================================================ FILE: SmartContracts/SimpleStorage.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // STATE VARIABLES // AND // LOCAL VARIABLES contract SimpleStorage{ } ================================================ FILE: SmartContracts/StateVariable.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // State Variables − Variables whose values are permanently stored in a contract storage. // Write State Variable cost gas fee // Read State Variables are free // always declare outside of function contract StateVariable{ uint public num; // write function setNum(uint number) external{ num = number; } // read function getNum() external view returns(uint){ return num; } } ================================================ FILE: SmartContracts/Struct.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; // Structs // You can define your own type by creating a struct. // They are useful for grouping together related data. // Structs can be declared outside of a contract and imported in another contract. contract Todos { struct Todo { string text; bool completed; } // Todo public myTodo = Todo("greeting",false); // Todo public _Todo = Todo({text : "greeting",completed : false}); // An array of 'Todo' structs Todo[] public todos; function create(string calldata _text) public { // 3 ways to initialize a struct // - calling it like a function todos.push(Todo(_text, false)); // key value mapping todos.push(Todo({text: _text, completed: false})); // initialize an empty struct and then update it Todo memory todo; todo.text = _text; // todo.completed = false; // todo.completed initialized to false todos.push(todo); } // Solidity automatically created a getter for 'todos' so // you don't actually need this function. function get(uint _index) public view returns (string memory text, bool completed) { Todo storage todo = todos[_index]; return (todo.text, todo.completed); } // update text function updateText(uint _index, string calldata _text) public { Todo storage todo = todos[_index]; todo.text = _text; } // update completed function toggleCompleted(uint _index) public { Todo storage todo = todos[_index]; todo.completed = !todo.completed; } } ================================================ FILE: SmartContracts/UseMathLib.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./MathLib.sol"; contract UseMath { uint public a = Math.add(2,4); } ================================================ FILE: SmartContracts/Variables.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; contract Variable{ //boolean //integer //unsign integer //string //bytes //address // range of uint8 0 - (2**8)-1 // uint8 public pos_number = 255; // int8 public number = 15; bool public han = true; // false address public hmoe = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4; // 0x00000 string public greet = "hello Blockchain people";// "" uint8 constant pos_number = 255; int8 constant number = 15; // uint = uint256 uint public num; //0 } ================================================ FILE: SmartContracts/ViewPure.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // View and Pure Functions // In View function: we can only read state variable and not write. // in Pure function: we can neither read nor write state variables. // In transaction function: we can write state variable. contract ViewPure{ uint public x = 5; function ViewFunc(uint _num) public view returns(uint){ return x + _num; } function PureFunc(uint a , uint b) public pure returns(uint){ return a+b; } function TraFunc() public returns(uint){ x = 10; return x; } }