diff --git a/step03_solidity_tutorial/contracts/Abstract/Abstract.sol b/step03_solidity_tutorial/contracts/Abstract/Abstract.sol new file mode 100644 index 0000000..5908d98 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Abstract/Abstract.sol @@ -0,0 +1,43 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +/* +Abstract Contract is one which contains at least one function without any implementation. +Such a contract is used as a base contract. Generally an abstract contract contains both implemented as well as abstract functions. +Derived contract will implement the abstract function and use the existing functions as and when required. +In case, a derived contract is not implementing the abstract function then this derived contract will be marked as abstract. +*/ +//IN Case we have Parent Contract with functionA which is not implimented in that contract but child contract will implement this function +// so for that we have to mark Parent Contract as abstract and make function virtual of Parent contract + +abstract contract ContractA { + function getResult() public pure returns(uint) { return 50; } + + function getData() public pure virtual returns(uint) ; +} + + +contract ContractB is ContractA { + function getData() public pure override returns(uint){ + return 12; + } + + + +} +contract ContractC { + uint value; + function checkfunctionA() public returns(uint256) { + //ContractA a = new ContractA();// we can't deploy abstract contract + ContractB b = new ContractB(); + value = b.getData(); + + } + function ResutlCheckfunction() public view returns(uint256) { + return value; + + } +} + \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Array/Array.sol b/step03_solidity_tutorial/contracts/Array/Array.sol new file mode 100644 index 0000000..cd70fff --- /dev/null +++ b/step03_solidity_tutorial/contracts/Array/Array.sol @@ -0,0 +1,46 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +// public private Variable Scope +contract String { + + + + + // 1. Dynamic arrays + // 2. Static arrays + // 3. Array arguments and return arrays from function + + //1. Dynamic Array + + uint[] public myArray; //Create, Read, Update, Delete + // This is dynamic size array here we are not specifing the array size + function storageArrays() public returns ( uint[] memory ) { + myArray.push(2); //add value in array + myArray.push(3); + myArray[0] = 20; // Updating array + + delete myArray[1]; // delete will not delete the value of given index + return myArray; + } + + //2. Static Array + function staticArray() public pure returns (uint[] memory) { + uint[] memory statArray = new uint[](10); //Create, Read, Update, Delete + // statArray.push(10)// we can't append value using push function in static type array + statArray[0] = 20; // add value in array + statArray[1]= 30; + + statArray[0] = 40; //update array + + delete statArray[1]; + return statArray; + } + function getIndexValue(uint _index) public view returns( uint value){ + // //get value of given index from array + value = myArray[_index]; + return value; + } +} + \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/CallBack function/callBackDemo.sol b/step03_solidity_tutorial/contracts/CallBack function/callBackDemo.sol new file mode 100644 index 0000000..4592803 --- /dev/null +++ b/step03_solidity_tutorial/contracts/CallBack function/callBackDemo.sol @@ -0,0 +1,28 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +import "./requestDemo.sol"; + +contract CallBackDemo{ + /* + // signature function + function testFunctionCall() public { + RequestDemo rc = new RequestDemo(); + rc.receivedRequest(address(this),this.receivedData.selector); + } + function receivedData(uint256 _value) public { + console.log("CallerDemo:: receivedData: value = ",_value); + } + */ + function testNewFunctionCall() public { + RequestDemo rc = new RequestDemo(); + rc.receivedFunctionRequest(this.newDataFunction); + } + function newDataFunction(uint256 _value) public view returns(uint256){ + console.log("CallerDemo:: receivedData: value = ",_value); + return _value*2; + } + + +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/CallBack function/requestDemo.sol b/step03_solidity_tutorial/contracts/CallBack function/requestDemo.sol new file mode 100644 index 0000000..cc2a8cb --- /dev/null +++ b/step03_solidity_tutorial/contracts/CallBack function/requestDemo.sol @@ -0,0 +1,27 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract RequestDemo{ + /* + // signature work + function receivedRequest(address _contractAddress , bytes4 callBackFunctionSignature ) public { + //////// + console.log("RequestDemo :: receivedRequest Started"); + (bool success, bytes memory data) = _contractAddress.call(abi.encodeWithSelector(callBackFunctionSignature,45)); + console.log("RequestDemo :: receivedRequest after success", success); + } + */ + // function (uint256) external view returns(uint256) myCall; + + function receivedFunctionRequest(function (uint256) external view returns(uint256) demoCall) public view { + // myCall = demoCall; + uint256 valueAfter = demoCall(23); + console.log("receivedFunctionRequest", valueAfter); + } + + // function hello() public{ + // myCall(12); + // } +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Constant/constant.sol b/step03_solidity_tutorial/contracts/Constant/constant.sol new file mode 100644 index 0000000..a3aeae3 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Constant/constant.sol @@ -0,0 +1,18 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +contract DemoConstant { + uint public constant AMOUNT = 45; // constant variable must need to be initialize + uint public immutable value; // if we initialized here so can't initialize later + // string public immutable name ; //we can't create immutable variable for other than value type + constructor(uint _value){ + value = _value; + + } + + function updateAmount() public { + // AMOUNT = 23; // we cann't assign value in the constant variable + // value = _value; can't change immutable variable + } +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Constructor/constructor.sol b/step03_solidity_tutorial/contracts/Constructor/constructor.sol new file mode 100644 index 0000000..814b6bd --- /dev/null +++ b/step03_solidity_tutorial/contracts/Constructor/constructor.sol @@ -0,0 +1,61 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + + + /* + Constructor is a special function declared using constructor keyword. It is an optional funtion and is used to initialize state variables of a contract. Following are the key characteristics of a constructor. + A contract can have only one constructor. + A constructor code is executed once when a contract is created and it is used to initialize contract state. + After a constructor code executed, the final code is deployed to blockchain. This code include public functions and code reachable through public functions. Constructor code or any internal method used only by constructor are not included in final code. + A constructor can be either public or internal. + A internal constructor marks the contract as abstract. + In case, no constructor is defined, a default constructor is present in the contract. + + */ + //default constructor + // constructor() { + // } + +contract ConstA { + //if we define constructor of just Child Contract this will work + //if we define contructor of parent Contract with argument we should define constructor of child contract otherwise solidity will not allow us + uint public value; + constructor(uint a){ + value = a; + + } + +} + + +//Derived Contract +contract ConstB is ConstA { + //if we don't define constructor so the default constructor is this +// constructor() ContractA() { + +// } + //so we have to pass the argument + // constructor() ContractA(2){ + + // } + + constructor(uint b) ConstA(b ) { + + } + function abc () public view returns(uint) { + return value; + } + + +} +contract ConstC { + function checkfunctionA(uint _value) public returns(uint) { + // ConstB b = new ConstB(); + ConstB b = new ConstB(_value); + return b.abc(); + } + +} + diff --git a/step03_solidity_tutorial/contracts/Demo Contract/Demo1.sol b/step03_solidity_tutorial/contracts/Demo Contract/Demo1.sol new file mode 100644 index 0000000..2aad0c1 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Demo Contract/Demo1.sol @@ -0,0 +1,44 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract Demo1 { + uint256 public balance; + string public name; + + constructor(string memory _name) { + name = _name; + } + + function getName() public view returns (string memory ) { + return name; + } + +} + +contract Demo2 { + address public demo1Address;//we create this variable of storing address of new contract + + function createExample(string memory _name) public returns(address ) { + /* + 1. This function create a new instanse of Demo1 Contract with the of d1 + 2. Update the demo1Address to address of d1 + 3. Return the Address of d1 + */ + Demo1 d1 = new Demo1(_name); + demo1Address = address(d1); + return address(d1); + } + + function getNameOfContract(address _addr1)public view returns(string memory) { + /* + 1. This function takes address + 2. Create the refrence of Demo1 and Pass this address to the Demo1 contract + 3. D1 return the Name of the given address + */ + Demo1 d1 = Demo1(_addr1); + return d1.getName(); + } + +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Demo1.sol b/step03_solidity_tutorial/contracts/Demo1.sol deleted file mode 100644 index 8c1a1b3..0000000 --- a/step03_solidity_tutorial/contracts/Demo1.sol +++ /dev/null @@ -1,34 +0,0 @@ -//SPDX-License-Identifier: Unlicense -pragma solidity ^0.8.0; - -import "hardhat/console.sol"; - -contract Demo1 { - - uint256 public balance; - string public name; - - constructor(string memory _name) { - name = _name; - } - - function getName() public view returns(string memory) { - return name; - } -} - -contract Demo2 { - - address public demo1Address; - function createExample(string memory _name) public returns (address){ - Demo1 d1 = new Demo1(_name); - demo1Address = address(d1); - return address(d1); - } - - function getNameOfContract(address _addr1) public view returns(string memory){ - Demo1 d1 = Demo1(_addr1); - return d1.getName(); - } - -} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Enums/enum.sol b/step03_solidity_tutorial/contracts/Enums/enum.sol new file mode 100644 index 0000000..b10a757 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Enums/enum.sol @@ -0,0 +1,52 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +/* +Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums. + +With the use of enums it is possible to reduce the number of bugs in your code. +*/ +contract Enum { + enum OrderStatus { + gettingReady, + onYourWay, + delivered + } + + OrderStatus status = OrderStatus.gettingReady; + + function getStatus()public view returns(OrderStatus) { + //This function is return the status of our order now it is 0 + return status; + } + + function updateOrderStatus(OrderStatus _status ) public { + // here we take argument _status with type of OrderStatus so whenever we pass argument which is not in the status so this will return error + //There is another way of doing this we will look inthe next senario which is define bellow + //This function is return the updated status of our order . + status = _status; + } + function verifyOrderStatus() public view returns(bool ) { + //This function will verify first than return the status of our order now it is 0 + return status == OrderStatus.delivered; + } + + enum FundingR { + SEED, + PRIVATE, + PUBLIC + } + FundingR Cround = FundingR.SEED; + function gerCFR()public view returns (FundingR) { + return Cround; + } + function changeR(FundingR _round)public { + //This is the another way + require(_round == FundingR.SEED || _round == FundingR.PUBLIC || _round == FundingR.PRIVATE, "Invalid Round Information"); + Cround = FundingR(_round); + + } + +} + diff --git a/step03_solidity_tutorial/contracts/Error Handling/ErrorHandling.sol b/step03_solidity_tutorial/contracts/Error Handling/ErrorHandling.sol new file mode 100644 index 0000000..d30f848 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Error Handling/ErrorHandling.sol @@ -0,0 +1,29 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +/* +Solidity provides various functions for error handling. Generally when an error occurs, the state is reverted back to its original state. Other checks are to prevent unauthorized code access. +Following are some of the important methods used in error handling − + assert(bool condition) − In case condition is not met, this method call causes an invalid opcode and any changes done to state got reverted. This method is to be used for internal errors. + require(bool condition) − In case condition is not met, this method call reverts to original state. - This method is to be used for errors in inputs or external components. + require(bool condition, string memory message) − In case condition is not met, this method call reverts to original state. - This method is to be used for errors in inputs or external components. It provides an option to provide a custom message. + revert() − This method aborts the execution and revert any changes done to the state. + revert(string memory reason) − This method aborts the execution and revert any changes done to the state. It provides an option to provide a custom message +*/ + +contract ErrorHandling{ + uint totalSupply =29999; + function mint(uint256 numberOfTokens) view public { + require(numberOfTokens < 10 ,"Number of tokens can not be more than 10"); + require(numberOfTokens > 5); + if (numberOfTokens > 5 && numberOfTokens >10){ + if(numberOfTokens > 7 && numberOfTokens < 9){ + revert("Number of tokens can not be more than 10"); + } + } + + assert(totalSupply < 10000); + } +} + diff --git a/step03_solidity_tutorial/contracts/Events/Events.sol b/step03_solidity_tutorial/contracts/Events/Events.sol new file mode 100644 index 0000000..aedb396 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Events/Events.sol @@ -0,0 +1,23 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +/* +Event is an inheritable member of a contract. An event is emitted, it stores the arguments passed in transaction logs. +These logs are stored on blockchain and are accessible using address of the contract till the contract is present on the blockchain. +An event generated is not accessible from within contracts, not even the one which have created and emitted them. +*/ + +contract Events{ + event DataUpdated(uint256 value, address from); + + function doSomeWork() public { + emit DataUpdated(34, msg.sender); + } + function mint(uint256 numberOfTokens) pure public { + require(numberOfTokens > 10 ,"Number of tokens can not be more than 10"); + + + } +} + diff --git a/step03_solidity_tutorial/contracts/Function Visibility/functionVisibility.sol b/step03_solidity_tutorial/contracts/Function Visibility/functionVisibility.sol new file mode 100644 index 0000000..e95187e --- /dev/null +++ b/step03_solidity_tutorial/contracts/Function Visibility/functionVisibility.sol @@ -0,0 +1,53 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract FunctionVisiblity1 { + //Function visibility allow us to who can access this function + // 1. Private + // 2. Public + // 3. External + + // Private + // we can only call function inside the contract it good to define private function with _ it's good but solidity doen't care of that + uint public value; + string public Name = "tariq"; + function _getValue() private view returns(uint) { + return value; + } + + //Internal + // we can access internal function inside the contract and the contract whcih is inherited from this contract but still can don't access function externaly + function getName() internal view returns(string storage) { + return Name; + } + //3. External + // we can only access outside the contract + function getValue() external view returns(uint) { + return value; + } + //4. Public we can acsees public funtion from inside the contract , from the contract which is inherited and also we can access it externaly + function setName(string memory _name) public { + Name = _name; + } +} + + + +contract FunctionVisiblity2 is FunctionVisiblity1 { + address public demo1Address;//we create this variable of storing address of new contract + + function AccessValue() public returns(string memory) { + + + //_getValue(); // we can't access private variable even this contract is inheritant from Demo1 + string memory newName =getName(); // we can access Internal function inside the inherit contract + // getValue(); //we can't access external function inside the contract and also the contract which is inherited from this contract + setName("Jokhio"); // here we can acces + return newName; + } + + + +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/If Else/ifElse.sol b/step03_solidity_tutorial/contracts/If Else/ifElse.sol new file mode 100644 index 0000000..a2a5a12 --- /dev/null +++ b/step03_solidity_tutorial/contracts/If Else/ifElse.sol @@ -0,0 +1,33 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract IfElse { + + function ifelse(uint _num)public pure returns(string memory) { + string memory oneDigit = "OneDigit Number"; + string memory TwoDigit = "TwoDigit Number"; + string memory ThreeDigit = "ThreeDigit Number"; + string memory NegativeValue = "Negative Value"; + string memory GreaterNumber = "number is greater than 999"; + if (_num > 0 && _num <10) { + return oneDigit; + } + else if (_num > 10 && _num <100) { + return TwoDigit; + } + else if (_num > 100 && _num< 1000 ) { + return ThreeDigit; + } + else if (_num <0 ) { + return NegativeValue ; + } + else { + return GreaterNumber; + + } +} + + +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Inheritance/Inheritance.sol b/step03_solidity_tutorial/contracts/Inheritance/Inheritance.sol new file mode 100644 index 0000000..b057253 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Inheritance/Inheritance.sol @@ -0,0 +1,110 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract A { + //private state variable + uint private data; + + //public state variable + uint public info; + + //constructor + constructor() { + info = 10; + } + //private function + function increment(uint a) private pure returns(uint) { return a + 1; } + + //public function + function updateData(uint a) public { data = a; } + + //Virtual Override + // if we declare same signature(name, access modifier , return ) of function in both contract so we need to make function of parent contract virtual and make the child function override + + function getData() public pure virtual returns(uint) { return 45; } + function compute(uint a, uint b) internal pure returns (uint) { return a + b; } + + } + + +//Derived Contract +contract B is A { + uint private result; + + function getComputedResult() public { + result = compute(3, 5); + } + function getResult() public view returns(uint) { return result; } + //function getData() public pure returns(uint) { return 45; }// now this will give error but in contract D will try to use virtual and override for that first we need to make getData of contract A virtual + //for that first we need to make getData of contract A virtual + function getData() public pure override returns(uint) { return 50; } + +} + + +contract C { + B b; + A a; + + + constructor() { + b = new B(); + a = new B(); + } + + + function checkfunctionA() public view returns(uint256) { + /* + //b.compute(5,6); //we can't access internal function outside the contract and child contract + //b.increment(4); // its private we can't acees this function + b.getResult(); // it's working we can call public funtion but not private and internal + + return b.getData(); + */ + /* + //now if we try to call the getresult function it will give error because now the type of variable a is A so contract A don't have getResult()function + + // a.getResult(); + return a.getData(); //getData is the function of contract A + */ + return a.getData(); + } + function checkfunctionB() public view returns(uint256) { + + return b.getData(); //getData is the function of contract A + } +} + + +contract ValueStorage { + uint public value = 2; + function update() virtual public { + value += 1; + } + +} +contract ValueStorage1 is ValueStorage { + function update() public virtual override { + value *= 2; + ValueStorage.update(); + } +} +contract ValueStorage2 is ValueStorage { + function update() public virtual override { + value += 10; + ValueStorage.update(); + // supper.update() this and above are the same + } +} +// multiple inheritence for the same herarci +contract ValueStorage3 is ValueStorage2 , ValueStorage1{ //right side will be used in super.update here the valueStorage1 will be call + + function update() public override(ValueStorage2,ValueStorage1) { + value *= 8; + super.update(); + + } +} + diff --git a/step03_solidity_tutorial/contracts/Interface/Interface.sol b/step03_solidity_tutorial/contracts/Interface/Interface.sol new file mode 100644 index 0000000..d6af405 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Interface/Interface.sol @@ -0,0 +1,50 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +/* +Interfaces are similar to abstract contracts and are created using interface keyword. +Following are the key characteristics of an interface. + Interface can not have any function with implementation. + Functions of an interface can be only of type external. + Interface can not have constructor. + Interface can not have state variables. + Interface can have enum, structs which can be accessed using interface name dot notation. +*/ +// IN Case we have Parent Contract with all functions is not implimented in that contract but child contract will implement these functions +// so for that we have to mark Parent Contract as interface and don't need to inplecitly mark function virtual of Parent contract +// make the child contract abstract it means this contract will not be deployable or implement the functions in child contract + + +interface Calculator { + function getResult() external pure returns(uint); + + function getData() external pure returns(uint) ; +} + +contract ContractD is Calculator{ + function getResult() public pure virtual override returns(uint) { + return 50; } + + function getData() public pure virtual override returns(uint){ + return 45; + } +} + +contract ContractE { + function checkinterface() public returns(uint) { + Calculator d = new ContractD(); + return d.getResult(); + } +} + +//IN Case we inherit new contract contractF from contractD and want to use the functions of contractD this will give error +//so for that we should mark the functions of contractD as virtual and override and functions of contract E virtual +contract ContractF is ContractD{ + function getResult() public pure override returns(uint) { + return 50; } + + function getData() public pure override returns(uint){ + return 45; + } +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Library/MyMatlib.sol b/step03_solidity_tutorial/contracts/Library/MyMatlib.sol new file mode 100644 index 0000000..0fbe1d8 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Library/MyMatlib.sol @@ -0,0 +1,13 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +library MyMatlib { + function sum(uint256 a, uint256 b) internal pure returns(uint256){ + return a+b; + } +} +//if you want to make function public so this will not be call and deploy directly +//so for use need to first deploy this MyMatlib library the attach this to contract + diff --git a/step03_solidity_tutorial/contracts/Library/library.sol b/step03_solidity_tutorial/contracts/Library/library.sol new file mode 100644 index 0000000..f11ce3f --- /dev/null +++ b/step03_solidity_tutorial/contracts/Library/library.sol @@ -0,0 +1,35 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +import "./MyMatlib.sol"; +/* +Libraries are similar to Contracts but are mainly intended for reuse. A Library contains functions which other contracts can call. Solidity have certain restrictions on use of a Library. +Following are the key characteristics of a Solidity Library. + Library functions can be called directly if they do not modify the state. That means pure or view functions only can be called from outside the library. + Library can not be destroyed as it is assumed to be stateless. + A Library cannot have state variables. + A Library cannot inherit any element. + A Library cannot be inherited. +*/ + + +contract ContractMath{ + event DataUpdated(uint256 value, address from); + function checkResult()public pure returns(uint256){ + return MyMatlib.sum(23, 23); + + } + // another way of using libraries + using MyMatlib for uint16; //it means type of first argument of all the functions will be part of uint256, we use this way + function checkResultUpdate()public pure returns(uint256){ + uint16 a =12; + return a.sum(23); // this is like MyMatlib.sum(12,23); + + } + function doSomeWork() public { + emit DataUpdated(34, msg.sender); + } + +} + diff --git a/step03_solidity_tutorial/contracts/Local function calls/Demolib.sol b/step03_solidity_tutorial/contracts/Local function calls/Demolib.sol new file mode 100644 index 0000000..867f3e3 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Local function calls/Demolib.sol @@ -0,0 +1,12 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +library Demolib{ + function doSomeThing() internal view { + console.log("Demo Library:: doSomething msg.sender ", msg.sender); + console.log("Demo Library :: doSomething tx.origin ", tx.origin); + console.log("Demo Library :: doSomething address ", address(this)); + } +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Local function calls/SecondContract.sol b/step03_solidity_tutorial/contracts/Local function calls/SecondContract.sol new file mode 100644 index 0000000..8f6d48d --- /dev/null +++ b/step03_solidity_tutorial/contracts/Local function calls/SecondContract.sol @@ -0,0 +1,18 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract SecondContract { + + uint public val = 5; + function doSomeThing(uint _value) public { + console.log("Second Contract:: doSomething msg.sender ", msg.sender); + console.log("Second Contract:: doSomething tx.origin ", tx.origin); + console.log("Second Contract:: doSomething address ", address(this)); + console.log("Second Contract:: doSomething _value ", _value); + + + val= _value; + } +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Local function calls/callFunctionDemo.sol b/step03_solidity_tutorial/contracts/Local function calls/callFunctionDemo.sol new file mode 100644 index 0000000..3897cd4 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Local function calls/callFunctionDemo.sol @@ -0,0 +1,36 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +import "./Demolib.sol"; + +contract CallFunctionDemo{ + address contractAddress; + constructor(address _contractAddress){ + contractAddress = _contractAddress; + } + uint public val = 4; + + function callerFunctionTest() public { + (bool success , bytes memory data ) = contractAddress.call(abi.encodeWithSignature("doSomeThing(uint256)",12)); + // (bool success , bytes memory data ) = contractAddress.call{gas: 10000000, value: 1000000000000000000000}(abi.encodeWithSignature("doSomeThing(uint256)",12)); // now we pass the gas like this + console.log("CallFunctionDemo :: callerfunctionTEST success = ", success); + // if we have code + // SecondContract abc = new SecondContract(); + // abc.doSomeThing(); + } + function delegatecallFunction() public { + (bool success , bytes memory data ) = contractAddress.delegatecall(abi.encodeWithSignature("doSomeThing(uint256)",12)); + console.log("delegateCallFunctionDemo :: delegatecallerfunctionTEST success = ", success); + console.log("value ", val); + } + function callFunctionLibrary() public view { + Demolib.doSomeThing(); + } + function staitcCallFunction() public view{ + // static function will not change the state of contract + (bool success , bytes memory data ) = contractAddress.staticcall(abi.encodeWithSignature("doSomeThing(uint256)",12)); + console.log("delegateCallFunctionDemo :: delegatecallerfunctionTEST success = ", success); + console.log("value ", val); +} +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Loop/loop.sol b/step03_solidity_tutorial/contracts/Loop/loop.sol new file mode 100644 index 0000000..aa8c341 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Loop/loop.sol @@ -0,0 +1,47 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +// public private Variable Scope +contract Loop { + + uint256 data = 1; + + function forloop() public { + + for (uint256 i; i<10; i++){ + data = data*2; + if (data >500){ + console.log(data); + continue; + } + } + } + + + function whileloop() public { + + uint age = data; + + + while(data<1000){ + age = data++; + console.log(age); // print sequence from 1 to 999 after 1000 loop will finish + } + } + + + + + function doWhile()public { + uint age ; + do{ + + data++; + age = data*2; + console.log("age", age); + } + while(data<10); + } + +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Math/math.sol b/step03_solidity_tutorial/contracts/Math/math.sol new file mode 100644 index 0000000..43c94c0 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Math/math.sol @@ -0,0 +1,39 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +/* +Solidity provides inbuilt mathematical functions as well. Following are heavily used methods − + +1. addmod(uint x, uint y, uint k) returns (uint) − computes (x + y) % k where the addition is performed with arbitrary precision and does not wrap around at 2256. +2. mulmod(uint x, uint y, uint k) returns (uint) − computes (x * y) % k where the addition is performed with arbitrary precision and does not wrap around at 2256. +*/ + +contract Math { + + function add1(uint256 a) public pure returns(uint){ + /* + This is our addmod function the basic difference between our custom of solidity builtin function + is our function wrap big number around at 2^256.but solidity buildin function does not wrap around at 2^256. + */ + uint256 max = 2 ** 256 -1; + return(max + max) % a; + + } + function add2(uint256 a) public pure returns(uint){ + uint256 max = 2 ** 256 -1; + return(max * max) % a; + + } + + function callAddMod(uint256 a) public pure returns(uint){ + uint256 max = 2 ** 256 -1; + return addmod(max, max, a); + } + function callMulMod(uint a) public pure returns(uint){ + uint256 max = 2 ** 256 -1; + return mulmod(max, max, a); + } + +} + diff --git a/step03_solidity_tutorial/contracts/Modifier/modifier.sol b/step03_solidity_tutorial/contracts/Modifier/modifier.sol new file mode 100644 index 0000000..6513f36 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Modifier/modifier.sol @@ -0,0 +1,32 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + + + + +contract Modifier { + + //Function Modifiers are used to modify the behaviour of a function. + // For example to add a prerequisite to a function. + + uint public counter; + address public treasureAddress; + address public owner; + constructor() { + owner = msg.sender; + } + + modifier onlyOwner() { + //this modifier check wheather the caller of the fuction is Owner or not + // if the caller of the function is the owner of the contract this will allow us to call the particular function where we use this modifier + require(msg.sender == owner, "ONly Owner Can Call" ); + _; + } + + function updateTreasureAddress(address _treasure) public onlyOwner { + treasureAddress = _treasure; + } + +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Overload/overload.sol b/step03_solidity_tutorial/contracts/Overload/overload.sol new file mode 100644 index 0000000..50a3485 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Overload/overload.sol @@ -0,0 +1,36 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract Overload { + /* + You can have multiple definitions for the same function name in the same scope. + The definition of the function must differ from each other by the types and/or the number of arguments in the argument list and sequence of the parameter. + You cannot overload function declarations that differ only by return type. + */ + + + function getSum(uint a, uint b) public pure returns(uint){ + return a + b; + } + function getSum(uint a, uint b, uint c) public pure returns(uint){ + return a + b + c; + } + function getSum(uint256 a, bool b) public pure returns(uint){ + return a ; + } + function getSum( bool b, uint256 a) public pure returns(uint){ + return a ; + } + + function callSumWithTwoArguments() public pure returns(uint){ + return getSum(1,2); + } + function callSumWithThreeArguments() public pure returns(uint){ + return getSum(1,2,3); + } + + +} + diff --git a/step03_solidity_tutorial/contracts/Receive Fallback/receiveFallback.sol b/step03_solidity_tutorial/contracts/Receive Fallback/receiveFallback.sol new file mode 100644 index 0000000..0891f96 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Receive Fallback/receiveFallback.sol @@ -0,0 +1,60 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract ReceiveFallback { + + uint256 public countReceive; + uint256 public countFallback; + + + mapping(address => uint256) public receiveBalance; + mapping(address => uint256) public fallbackBalance; + function addSome() public { + countReceive+=20; + countFallback+=20; + + } +/* +Fallback: +The fallback function now has a different syntax, declared using fallback() external [payable] {…} (without the function keyword). +This function cannot have arguments,cannot return anything and must have external visibility. The fallback function always receives data, + but to also receive Ether, you should mark it as payable. + +typically used the fallback function to handle logic in two scenarios: + +contract received ether and no data +contract received data but no function matched the function called + +Receive : +Receive is function same as fallback we use it when Contract Receives ethers but no data + + + */ + + receive () external payable { + countReceive++; + receiveBalance[msg.sender] += msg.value; + } + + + + fallback () external payable { + countFallback++; + fallbackBalance[msg.sender] += msg.value; + + } + + +} + +contract ReceiveFallback2 { + + + function testFunctioncall(address _contractAddress, string memory _signature) public { + (bool success,) = _contractAddress.call(abi.encodeWithSignature((_signature))); + require(success); + } +} + diff --git a/step03_solidity_tutorial/contracts/Greeter.sol b/step03_solidity_tutorial/contracts/Solidity First Application/Greeter.sol similarity index 96% rename from step03_solidity_tutorial/contracts/Greeter.sol rename to step03_solidity_tutorial/contracts/Solidity First Application/Greeter.sol index 34ceabc..efffb8f 100644 --- a/step03_solidity_tutorial/contracts/Greeter.sol +++ b/step03_solidity_tutorial/contracts/Solidity First Application/Greeter.sol @@ -3,7 +3,7 @@ pragma solidity ^0.8.0; import "hardhat/console.sol"; -contract Greeter { +contract Greeter { string private greeting; constructor(string memory _greeting) { diff --git a/step03_solidity_tutorial/contracts/SolidityTest.sol b/step03_solidity_tutorial/contracts/SolidityTest.sol deleted file mode 100644 index 0eb1965..0000000 --- a/step03_solidity_tutorial/contracts/SolidityTest.sol +++ /dev/null @@ -1,43 +0,0 @@ -//SPDX-License-Identifier: Unlicense -pragma solidity ^0.8.0; - -import "hardhat/console.sol"; - -contract SolidityTest { - - enum FreshJuiceSize { SMALL, MEDIUM, LARGE, EXTRALARGE } - - enum FundingRounds { - SEED, - PRIVATE, - PUBLIC - } - - uint256 abc = 45; - - FreshJuiceSize juice = FreshJuiceSize.MEDIUM; - - FundingRounds currentRound = FundingRounds.SEED; - - function getCurrentFundingRound() public view returns (FundingRounds) { - return currentRound; - } - - function changeRound(uint256 _round) public { - require(_round >= 0 && _round <=2,"Invalid Round Information"); - currentRound = FundingRounds(_round); - } - - function getJuice() public view returns(FreshJuiceSize) { - return juice; - } - - function updateJuiceSize(FreshJuiceSize _juice) public { - juice = _juice; - } - - function verifyJuiceSize() public view returns (bool) { - return juice == FreshJuiceSize.EXTRALARGE; - } - -} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/SolidityTest2.sol b/step03_solidity_tutorial/contracts/SolidityTest2.sol deleted file mode 100644 index 06adfe0..0000000 --- a/step03_solidity_tutorial/contracts/SolidityTest2.sol +++ /dev/null @@ -1,79 +0,0 @@ -//SPDX-License-Identifier: Unlicense -pragma solidity ^0.8.0; - -import "hardhat/console.sol"; - -contract SolidityTest2 { - - enum FundingRounds { - SEED, - PRIVATE, - PUBLIC - } - - struct FundingRoundDetails { - uint256 fundingRequired; - FundingRounds round; - } - - FundingRoundDetails[] public allRounds; - - mapping(uint256 => FundingRoundDetails) fundingRounds; - - mapping(address => FundingRoundDetails) userRounds; - - mapping(address => mapping(uint256=>bool)) someMapping; - - uint256 roundCounter; - - struct UserInfo { - string name; - uint256 age; - mapping(address=>uint256) fundingReceived; - } - - mapping(address=>UserInfo) users; - - function addUser(string memory _name, uint256 _age) public { - //UserInfo memory _user = UserInfo("Zia Khan", 30); - - UserInfo storage _user = users[msg.sender]; - _user.name= _name; - _user.age = _age; - } - - function provideFunding(address _user, uint256 _amount) public { - UserInfo storage _userInfo = users[_user]; - _userInfo.fundingReceived[msg.sender] = _amount; - } - - function addFundingRounds() public { - FundingRoundDetails memory details1 = FundingRoundDetails(10000, FundingRounds.SEED); - FundingRoundDetails memory details2 = FundingRoundDetails(20000, FundingRounds.PRIVATE); - FundingRoundDetails memory details3 = FundingRoundDetails(30000, FundingRounds.PUBLIC); - allRounds.push(details1); - allRounds.push(details2); - allRounds.push(details3); - - - fundingRounds[++roundCounter] = details1; - fundingRounds[++roundCounter] = details2; - fundingRounds[++roundCounter] = details3; - } - - function addRound(uint256 amount, uint256 round) public { - roundCounter++; - fundingRounds[roundCounter] = FundingRoundDetails(amount, FundingRounds(round)); - - userRounds[msg.sender] = FundingRoundDetails(amount, FundingRounds(round)); - - } - - function getMyRoundInfo() public view returns(FundingRoundDetails memory) { - return userRounds[msg.sender]; - } - - function getRequiredFundingForRound(uint256 _roundNumber) public view returns(uint256){ - return allRounds[_roundNumber].fundingRequired; - } -} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/SolidityTest3.sol b/step03_solidity_tutorial/contracts/SolidityTest3.sol deleted file mode 100644 index 4746805..0000000 --- a/step03_solidity_tutorial/contracts/SolidityTest3.sol +++ /dev/null @@ -1,26 +0,0 @@ -//SPDX-License-Identifier: Unlicense -pragma solidity ^0.8.0; - -import "hardhat/console.sol"; - -contract SolidityTest3 { - - - uint256 amount = 1 ether; - uint256 amount1 = 1_000_000_000_000_000_000; - uint256 amount2 = 1e18; - uint256 amount3 = 5_600_000_000_000_000_000; - - uint256 time = 24 hours; - uint256 week = 7 days; - - function applyConversion() public pure returns(uint256){ - //uint256 a = 45; - //uint8 b = uint8(a); - int8 a = -3; - uint8 b = uint8(a); - - return b; - - } -} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/SolidityTest4.sol b/step03_solidity_tutorial/contracts/SolidityTest4.sol deleted file mode 100644 index f3f4b46..0000000 --- a/step03_solidity_tutorial/contracts/SolidityTest4.sol +++ /dev/null @@ -1,56 +0,0 @@ -//SPDX-License-Identifier: Unlicense -pragma solidity ^0.8.0; - -import "hardhat/console.sol"; - -contract SolidityTest4 { - - uint256 public counter; - address public treasureAddress; - address public owner; - uint256 public price = 0.01 ether; - - constructor() { - owner = msg.sender; - } - - modifier onlyOwner() { - require(msg.sender == owner, "Only Owner Can call"); - _; - } - - modifier verifyAmount(uint256 _amount) { - require(price == _amount, "Incorrect value provided"); - _; - } - - function updateAmount(uint256 _value) public verifyAmount(_value) { - price = _value; - counter++; - } - - function updateTreasureAddress(address _treasury) public onlyOwner { - treasureAddress = _treasury; - } - - - function doSomething() public view returns(uint256) { - return counter; - } - - function checkPureFunction(uint256 val) public pure returns(uint256) { - return val * 23; - } - - function multiVal() public view returns(uint256, bool) { - return (counter, false); - } - - function multiVal2() public view returns(uint256 index, bool isPaid) { - index = 4 * counter; - isPaid = true; - //// - //// - } - -} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/SolidityTest5.sol b/step03_solidity_tutorial/contracts/SolidityTest5.sol deleted file mode 100644 index 7cac5fe..0000000 --- a/step03_solidity_tutorial/contracts/SolidityTest5.sol +++ /dev/null @@ -1,39 +0,0 @@ -//SPDX-License-Identifier: Unlicense -pragma solidity ^0.8.0; - -import "hardhat/console.sol"; - -contract SolidityTest5 { - - uint256 public countReceive; - uint256 public countFallback; - - mapping(address => uint256) public receiveBalance; - mapping(address => uint256) public fallbackBalance; - - function addSome() public { - countReceive+=20; - countFallback+=20; - } -/* - receive () external payable { - countReceive++; - receiveBalance[msg.sender]+= msg.value; - } - - fallback() external { - countFallback++; - //fallbackBalance[msg.sender] += msg.value; - } -*/ -} - - -contract SolidityTest6 { - - function testFunctionCall(address _contractAddress, string memory _signature) public { - (bool success,) = _contractAddress.call(abi.encodeWithSignature(_signature)); - require(success); - } - -} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/SolidityTest6.sol b/step03_solidity_tutorial/contracts/SolidityTest6.sol deleted file mode 100644 index ca260b6..0000000 --- a/step03_solidity_tutorial/contracts/SolidityTest6.sol +++ /dev/null @@ -1,75 +0,0 @@ -//SPDX-License-Identifier: Unlicense -pragma solidity ^0.8.0; - -import "hardhat/console.sol"; - -contract SolidityTest7 { - - function add1(uint256 a, uint256 b, uint256 c) public pure returns (uint256) { - uint256 max = 2 ** 256 - 1; - - return (max + max) % c; - } - - function add2(uint256 a, uint256 b, uint256 c) public pure returns (uint256) { - uint256 max = 2 ** 256 - 1; - return addmod(max, max, c); - } - - address payable public richest; - uint public mostSent; - mapping(address => uint256) pendingWithdrawals; - - constructor() { - richest = payable(msg.sender); - } - - function setAddress(address _add) public { - richest = payable(_add); - } - - /* - function becomeRichest() public payable returns (bool) { - if (msg.value > mostSent) { - // Insecure practice - richest.transfer(msg.value); - richest = payable(msg.sender); - mostSent = msg.value; - return true; - } else { - return false; - } - } - */ - - function becomeRichest() public payable returns (bool) { - if (msg.value > mostSent) { - pendingWithdrawals[richest] += msg.value; - richest = payable(msg.sender); - mostSent = msg.value; - return true; - } else { - return false; - } - } - function withdraw() public { - uint amount = pendingWithdrawals[msg.sender]; - pendingWithdrawals[msg.sender] = 0; - payable(msg.sender).transfer(amount); - //payable(msg.sender).call{value: amount, gas: 250000}(""); - } - -} - -contract DemoTest { - function testValue () public { - - } - - function getFunds (address addressOfContract) public { - SolidityTest7 abc = SolidityTest7(addressOfContract); - abc.withdraw(); - } - -} - diff --git a/step03_solidity_tutorial/contracts/Special Variable/SolidityTest.sol b/step03_solidity_tutorial/contracts/Special Variable/SolidityTest.sol new file mode 100644 index 0000000..351ef08 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Special Variable/SolidityTest.sol @@ -0,0 +1,26 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +/* +Special variables are globally available variables and provides information about the blockchain. Following is the list of special variables − +Sr.No. Special Variable & Description +1. blockhash(uint blockNumber) returns (bytes32) +Hash of the given block - only works for 256 most recent, excluding current, blocks. +2. block.coinbase (address payable) Current block miner's address. +3. block.difficulty (uint) current block difficulty. +4. block.gaslimit (uint) Current block gaslimit. +5. block.number (uint) Current block number. +6. block.timestamp Current block timestamp as seconds since unix epoch. +7. gasleft() returns (uint256) Remaining gas. +8. msg.data (bytes calldata) Complete calldata. +*/ +contract SolidityTest { + constructor() { + } + + function getBlockNum() public view returns(uint){ + uint256 blockNumber = block.number; + return blockNumber; + } +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/String/string.sol b/step03_solidity_tutorial/contracts/String/string.sol new file mode 100644 index 0000000..ecb6d71 --- /dev/null +++ b/step03_solidity_tutorial/contracts/String/string.sol @@ -0,0 +1,32 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +// public private Variable Scope +contract StringType { + + + + function getName() public pure returns(string memory) { + string memory firstName = "Tariq"; + string memory lastName = "Nawaz"; + + string memory name; + + name = string(abi.encodePacked(firstName,lastName)); + // string memory FullName = string(abi.encodePacked(fastName,lastName)); + // bytes memory byteName = bytes(FullName); + // string memory strName = string(byteName); + return name; + + } + function getBytesName(string memory firstName, string memory lastName)public pure returns( bytes memory ) { + string memory FullName = string(abi.encodePacked(firstName,lastName)); + bytes memory byteName = bytes(FullName); + // string memory strName = string(byteName); + return (byteName); + } + + +} + \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Struct/struct.sol b/step03_solidity_tutorial/contracts/Struct/struct.sol new file mode 100644 index 0000000..a9bb5c1 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Struct/struct.sol @@ -0,0 +1,106 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +/* +Mapping is a reference type as arrays and structs. Following is the syntax to declare a mapping type. +mapping(_KeyType => _ValueType) +Where +_KeyType − can be any built-in types plus bytes and string. No reference type or complex objects are allowed. +_ValueType − can be any type. +*/ +/* +Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums. +With the use of enums it is possible to reduce the number of bugs in your code. +For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large. +*/ + + +contract Struct { + enum FundingRounds { + SEED, + PRIVATE, + PUBLIC + } + + struct FundingRoundDetails{ + uint256 funding; + FundingRounds round; + } + FundingRoundDetails[] public allRounds; + + function addFundingR()public { + FundingRoundDetails memory details1 = FundingRoundDetails(1000,FundingRounds.SEED); + FundingRoundDetails memory details2 = FundingRoundDetails(2000,FundingRounds.SEED); + FundingRoundDetails memory details3 = FundingRoundDetails(3000,FundingRounds.SEED); + allRounds.push(details1); + allRounds.push(details2); + allRounds.push(details3); + } + + function getFundingR(uint256 _round) public view returns (uint256) { + return allRounds[_round].funding; + } + + + //struct inside mapping + mapping(uint256 => FundingRoundDetails) private fundingRounds; + uint256 public roundCounter; + mapping(address => FundingRoundDetails) private userRounds; + + function addRound(uint256 _amount, uint256 _round)public { + roundCounter++; + fundingRounds[roundCounter] = FundingRoundDetails(_amount, FundingRounds(_round)); + + userRounds[msg.sender] = FundingRoundDetails(_amount, FundingRounds(_round)); + } + function getFunding(uint _roundNumber) public view returns(uint256) { + return fundingRounds[_roundNumber].funding; + } + function getMyRoundInfo(uint256 _round) public view returns(FundingRoundDetails memory ){ + return fundingRounds[_round]; + } + function senderRoundInfo()public view returns(FundingRoundDetails memory) { + return userRounds[msg.sender]; + } + + + //now combination of stuck, mapping + //first mapping inside struct + struct UserInfo { + string name; + uint256 age; + mapping(address => uint256) fundingReceived; + } + + mapping(address =>UserInfo) public users; + function addUser() public { + // UserInfo memory _user = UserInfo("Zia KHan, 30) + UserInfo storage _user = users[msg.sender]; + + _user.name = "Tariq"; + _user.age = 32; + } + + function provideFunding(uint256 _amount,address _user)public returns(uint256) { + UserInfo storage _userInfo = users[_user]; + _userInfo.fundingReceived[msg.sender] = _amount; + _userInfo.fundingReceived[msg.sender] = 2; + return _userInfo.fundingReceived[msg.sender]; + } + + //mapping inside mapping + // enum RollInSchool{ + // STUDENT, + // TEACHER + // } + // mapping(uint=> mapping(string=>RollInSchool)) roll; + + // function addRoll(uint _index, string memory _name, RollInSchool _roll)public { + // roll[_index][_name]= _roll; + + // } + + + +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/Types/Types.sol b/step03_solidity_tutorial/contracts/Types/Types.sol new file mode 100644 index 0000000..4b0bd3d --- /dev/null +++ b/step03_solidity_tutorial/contracts/Types/Types.sol @@ -0,0 +1,38 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract VarTypes { + + //1. fixed-size types + bool public isReady; //the value of boolean will be true/false + + //Signed and unsigned integers of varying sizes. + int public a = 2; //Signed int from 8 bits to 256 bits. int256 is the same as int we can sign negative value. + uint public b = 4; // Unsigned int from 8 bits to 256 bits. uint256 is the same as uint, we can't sign negative value. + + address public recipent; //we use address type for contract address + bytes32 public data;// This is intermediatory type More preferred way is to use byte types instead of String as string operation requires more gas as compared to byte operation. + + //2. variable-size types + string public name; //string for character but we use bytes instead of string + bytes public _data; // generalization of bytes type + uint[] public amounts; // array for uint types but we can't assign string into it. + mapping(uint => string) public users; //This is very similar as javascript object + + struct User { + uint id; + string name; + uint[] friendIds; + } + enum Color { + RED, + GREEN, + BLUE + } + //This is the high level overview of variable type in solidity but we will see all of these in detail in the next few tutorial + + +} + diff --git a/step03_solidity_tutorial/contracts/Variable/Variable.sol b/step03_solidity_tutorial/contracts/Variable/Variable.sol new file mode 100644 index 0000000..2233969 --- /dev/null +++ b/step03_solidity_tutorial/contracts/Variable/Variable.sol @@ -0,0 +1,41 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +contract VariableScope { + // Variable Scope + // 1. Private Variable + uint256 private age; //this is only call by this contract + // 1. Internal Variable + //Internal variable can be call by this contract and the contract which is inherited by this contract + uint256 internal height; + // 3. Public + // Public variable can be called by anyone + string public Name = "tariq jokhio"; // by default this is state level variable + + function updateAge(uint _age) public { + age = _age; + height = 6; + + } +} + + +contract Variable is VariableScope { + //Types of Variable + + //1. State Variables − Variables whose values are permanently stored in a contract storage. + + //2. Local Variables − Variables whose values are present till function is executing. + + //3. Global Variables − Special variables exists in the global namespace used to get information about the blockchain. + //one example of Global variable is msg.sender (address payable) + + function updateHeight(uint _height) public { + //height = _height / age; //Solidity doesn't allow us to call private variable + height = _height; + } + function getName() public view returns(string memory) { + return Name; + } +} \ No newline at end of file diff --git a/step03_solidity_tutorial/contracts/View Pure Functions/pure,view.sol b/step03_solidity_tutorial/contracts/View Pure Functions/pure,view.sol new file mode 100644 index 0000000..fc000e7 --- /dev/null +++ b/step03_solidity_tutorial/contracts/View Pure Functions/pure,view.sol @@ -0,0 +1,44 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract Practice { + //1. view: when we use view the solidity use eth_call + //2. pure: when we use pure the solidity use eth_call + //3. When we don't use view or pure the solidity use eth_sendTrasaction + //4. if we call view or pure function inside another function which is transaction function so call of view and pure function + // treated as transaction function call which means it consume gas + + uint value = 4; + + function getValue() public view returns(uint){ + //View keyword is for read only means we cann't change value of state variable and we cann't perform any computation. + // value = 3;// if we are trying to change state varaible but we couldn't this will give us error. + return value; + } + function setValue() external returns(uint){ + // Note gas consume by this will be high + //we can change value of state variable or modifie the blockchain without defining the view and pure + value = getValue(); + value = value + 2; + + return value; + } + function setValue1() external returns(uint){ + // Note gas consume by the function will be low as compare to upper function + // function without calling view and pure function + value = value + 2; + return value; + } + + function getValue1() external pure returns(uint){ + // it will just do some computation + uint value1; + return value1 +1 ; + } + + + +} + diff --git a/step03_solidity_tutorial/contracts/WithDrawal Pattern/withdrawalPattern.sol b/step03_solidity_tutorial/contracts/WithDrawal Pattern/withdrawalPattern.sol new file mode 100644 index 0000000..06d7dd9 --- /dev/null +++ b/step03_solidity_tutorial/contracts/WithDrawal Pattern/withdrawalPattern.sol @@ -0,0 +1,53 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; + +contract WithDrawal { + address payable public richest; + uint public mostSent; + mapping(address => uint) public pendingWithDrawals; + constructor(){ + richest = payable(msg.sender); + } + + function setAddress( address _add) public { + richest = payable(_add); + } + + function becomeRichest() public payable returns(bool ){ + if (msg.value > mostSent){ + pendingWithDrawals[richest] += msg.value; + richest = payable(msg.sender); + mostSent = msg.value; + return true; + } + else{ + return false; + + } + } + function withDraw() public{ + uint amount = pendingWithDrawals[msg.sender]; + pendingWithDrawals[msg.sender] = 0; + payable(msg.sender).transfer(amount); + } + + +} + +contract Demo { + function testValue () public { + + } + + function getFunds(address _contractAddress) public { + WithDrawal abc = WithDrawal(_contractAddress); + abc.withDraw(); + + } + receive() external payable { + + } +} + diff --git a/step03_solidity_tutorial/contracts/abiEncodingFunction/abiEncode.sol b/step03_solidity_tutorial/contracts/abiEncodingFunction/abiEncode.sol new file mode 100644 index 0000000..71cdf80 --- /dev/null +++ b/step03_solidity_tutorial/contracts/abiEncodingFunction/abiEncode.sol @@ -0,0 +1,81 @@ +//SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.0; + +import "hardhat/console.sol"; +/* +1. abi.encode(...) returns (bytes) : + ABI encodes the given arguments. Arguments can be of any type. It returns the encoded data as bytes . +2. abi.encodePacked(...) returns (bytes) : + This performs packed encoding of the given arguments. Arguments can be of any type. It returns the packed encoding of the data as bytes . +3. abi.encodeWithSelector(bytes4 selector, ...) returns (bytes) : + ABI encodes the given arguments. The first argument takes a function selector and from the second onward it takes any data type. It returns the encoded data as bytes . +4. abi.encodeWithSignature(string signature, ...) returns (bytes) : + This is equivalent to abi.encodeWithSelector(bytes4(keccak256(signature), ...) . +*/ + +contract ABIEncodeExample { + address public addr; + uint public uInt; //uint = uint256 + uint8 public uInt8; + uint16 public uInt16; + + constructor() { + addr = 0x611B947ec990Ba4e1655BF1A37586467144A2D65; + uInt = 20; + uInt8 = 25; + uInt16 = 30; + } + + function encode() public view returns (bytes memory) { + + //Returns following concatenated + // Prefix: 0x + // addr : 000000000000000000000000611b947ec990ba4e1655bf1a37586467144a2d65 + // uInt : 0000000000000000000000000000000000000000000000000000000000000014 + // uInt8 : 0000000000000000000000000000000000000000000000000000000000000019 + // uInt16: 000000000000000000000000000000000000000000000000000000000000001e + return abi.encode(addr, uInt, uInt8, uInt16); + } + + function encodePacked() public view returns (bytes memory) { + // Prefix: 0x + // addr : 611b947ec990ba4e1655bf1a37586467144a2d65 + // uInt : 0000000000000000000000000000000000000000000000000000000000000014 + // uInt8 : 19 + // uInt16: 001e + return abi.encodePacked(addr, uInt, uInt8, uInt16); + //Packing of uint as per their size + } + + function encodeWithSelector() public view returns (bytes memory) { + // Prefix : 0x + // selector: 13bd8af1 + // uInt : 0000000000000000000000000000000000000000000000000000000000000014 + // uInt8 : 0000000000000000000000000000000000000000000000000000000000000019 + return abi.encodeWithSelector(this.testMethod.selector, uInt, uInt8); + } + + function encodeWithSelectorSignature() public view returns (bytes memory) { + // Prefix : 0x + // selector: 13bd8af1 + // uInt : 0000000000000000000000000000000000000000000000000000000000000014 + // uInt8 : 0000000000000000000000000000000000000000000000000000000000000019 + return abi.encodeWithSelector(bytes4(keccak256("testMethod(uint256,uint8)")), uInt, uInt8); + } + + function encodeWithSignature() public view returns (bytes memory) { + // Prefix : 0x + // selector: 13bd8af1 + // uInt : 0000000000000000000000000000000000000000000000000000000000000014 + // uInt8 : 0000000000000000000000000000000000000000000000000000000000000019 + return abi.encodeWithSignature("testMethod(uint256,uint8)", uInt, uInt8); + } + + function testMethod(uint _a, uint8 _b) public view { + //... + //Just to remove compilation warnings + assert(_a > 0); + assert(_b > 0); + assert(uInt > 0); + } +} diff --git a/step03_solidity_tutorial/scripts/Abstract/abstract.ts b/step03_solidity_tutorial/scripts/Abstract/abstract.ts new file mode 100644 index 0000000..61398be --- /dev/null +++ b/step03_solidity_tutorial/scripts/Abstract/abstract.ts @@ -0,0 +1,22 @@ +import { ethers } from "hardhat"; +import { ContractD__factory, ContractD, ContractE__factory, ContractE, ContractF__factory, ContractF, ContractC__factory, ContractC } from "../../typechain"; + +async function main() { + + const Abstract:ContractC__factory = await ethers.getContractFactory("ContractC"); + const abstract:ContractC = await Abstract.deploy(); + await abstract.deployed(); + + console.log("ContractD deployed to:", abstract.address); + + await abstract.checkfunctionA() + console.log("Data is ", await (await abstract.ResutlCheckfunction()).toNumber()); +} + + +// We recommend this pattern to be able to use async/await everywhere +// and properly handle errors. +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/step03_solidity_tutorial/scripts/Array/Array.ts b/step03_solidity_tutorial/scripts/Array/Array.ts new file mode 100644 index 0000000..9733e44 --- /dev/null +++ b/step03_solidity_tutorial/scripts/Array/Array.ts @@ -0,0 +1,25 @@ +import { ethers } from "hardhat"; +import { string } from "hardhat/internal/core/params/argumentTypes"; +import { Practice, Practice__factory, String__factory } from "../../typechain"; +import { SolidityTest__factory } from "../../typechain/factories/SolidityTest__factory"; + +async function main() { + + const StringC : String__factory = await ethers.getContractFactory("String"); + const stringC = await StringC.deploy(); + + await stringC.deployed(); + + console.log("Contract deployed to:", stringC.address); + const data = await stringC.getName(); + console.log("data of age is ", data.toString()); + + const name = await stringC.getBytesName("Tariq", "Nawaz"); + console.log("data of age is ", name.toString()); + + +} +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/step03_solidity_tutorial/scripts/Call Function/callfunction.ts b/step03_solidity_tutorial/scripts/Call Function/callfunction.ts new file mode 100644 index 0000000..0e6ae4e --- /dev/null +++ b/step03_solidity_tutorial/scripts/Call Function/callfunction.ts @@ -0,0 +1,41 @@ +import { ethers } from "hardhat"; +import { ContractD__factory, ContractD, ContractE__factory, ContractE, ContractF__factory, ContractF, ContractC__factory, ContractC, CallFunctionDemo__factory, CallFunctionDemo, SecondContract__factory, SecondContract, CallBackDemo } from "../../typechain"; +import { CallBackDemo__factory } from "../../typechain/factories/CallBackDemo__factory"; + +async function main() { + + const SecondContract:SecondContract__factory = await ethers.getContractFactory("SecondContract"); + const secondContract:SecondContract = await SecondContract.deploy(); + await secondContract.deployed(); + + console.log("SecondContract deployed to:", secondContract.address); + + const CallFunction:CallFunctionDemo__factory = await ethers.getContractFactory("CallFunctionDemo"); + const callFunction:CallFunctionDemo = await CallFunction.deploy(secondContract.address); + await callFunction.deployed(); + + console.log("callFunction deployed to:", callFunction.address); + console.log("value Before", await secondContract.val()); + // const txt1 = await callFunction.callerFunctionTest() + console.log("value after", await secondContract.val()); + console.log("value of callfunctionDemo before", await callFunction.val()); + const txt2 = await callFunction.delegatecallFunction(); + console.log("value of callfunctionDemo after", await callFunction.val()); + // console.log("Data is ",txt ); + /* + this is for static call + const txt3 = await callFunction.staitcCallFunction(); + console.log("value of callfunctionDemo after", await callFunction.val()); + */ + // for library call function + await callFunction.callFunctionLibrary(); //calling the library function is work like a delegate call + +} + + +// We recommend this pattern to be able to use async/await everywhere +// and properly handle errors. +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/step03_solidity_tutorial/scripts/CallBack Function/callbackFunction.ts b/step03_solidity_tutorial/scripts/CallBack Function/callbackFunction.ts new file mode 100644 index 0000000..eb62d1f --- /dev/null +++ b/step03_solidity_tutorial/scripts/CallBack Function/callbackFunction.ts @@ -0,0 +1,42 @@ +import { ethers } from "hardhat"; +import { ContractD__factory, ContractD, ContractE__factory, ContractE, ContractF__factory, ContractF, ContractC__factory, ContractC, CallFunctionDemo__factory, CallFunctionDemo, SecondContract__factory, SecondContract, CallBackDemo, RequestDemo__factory, RequestDemo } from "../../typechain"; +import { CallBackDemo__factory } from "../../typechain/factories/CallBackDemo__factory"; + +async function main() { + + // for callback function call + /* + //signaturefunction + const CallBackDemo:CallBackDemo__factory = await ethers.getContractFactory("CallBackDemo"); + const callBackDemo:CallBackDemo = await CallBackDemo.deploy(); + await callBackDemo.deployed(); + + console.log("callFunction deployed to:", callBackDemo.address); + + await callBackDemo.testFunctionCall(); + */ + const CallBackDemo:CallBackDemo__factory = await ethers.getContractFactory("CallBackDemo"); + const callBackDemo:CallBackDemo = await CallBackDemo.deploy(); + await callBackDemo.deployed(); + + console.log("callFunction deployed to:", callBackDemo.address); + + await callBackDemo.testNewFunctionCall(); + + const RequestDemo:RequestDemo__factory = await ethers.getContractFactory("RequestDemo"); + const requestDemo:RequestDemo = await RequestDemo.deploy(); + await callBackDemo.deployed(); + + console.log("requestDemo deployed to:",requestDemo.address); + // const txt1 = await requestDemo.hello(); + // console.log("txt1 ", txt1); + +} + + +// We recommend this pattern to be able to use async/await everywhere +// and properly handle errors. +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/step03_solidity_tutorial/scripts/Constructor/constructor.ts b/step03_solidity_tutorial/scripts/Constructor/constructor.ts new file mode 100644 index 0000000..16f840e --- /dev/null +++ b/step03_solidity_tutorial/scripts/Constructor/constructor.ts @@ -0,0 +1,18 @@ +import { ethers } from "hardhat"; +import { ConstC, ConstC__factory, Demo2, Demo2__factory, Overload__factory } from "../../typechain"; + +async function main() { + + const ConstC: ConstC__factory = await ethers.getContractFactory("ConstC"); + const constC:ConstC = await ConstC.deploy(); + + await constC.deployed(); + + console.log("Address of deployed contract is :", constC.address); + const txt1 =await constC.checkfunctionA(6); + console.log("txt1" ,txt1); +} +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/step03_solidity_tutorial/scripts/Demo contract/contract.ts b/step03_solidity_tutorial/scripts/Demo contract/contract.ts new file mode 100644 index 0000000..67c87fa --- /dev/null +++ b/step03_solidity_tutorial/scripts/Demo contract/contract.ts @@ -0,0 +1,31 @@ +import { ethers } from "hardhat"; +import { Demo2, Demo2__factory, Overload__factory } from "../../typechain"; +import { SolidityTest__factory } from "../../typechain/factories/SolidityTest__factory"; + +async function main() { + + const Contract: Demo2__factory = await ethers.getContractFactory("Demo2"); + const contract:Demo2 = await Contract.deploy(); + + await contract.deployed(); + + console.log("Address of deployed contract Demo2 is :", contract.address); + const txt1 =await contract.createExample("First"); + const demoAddress1 = await contract.demo1Address(); + console.log("Address of First Instanse of demo1 is ",demoAddress1); + const txt2 =await contract.createExample("Second"); + const demoAddress2 = await contract.demo1Address(); + console.log("Address of Second Instanse of demo1 is ",demoAddress2); + const txt3 =await contract.createExample("Third"); + const demoAddress3 =await contract.demo1Address(); + console.log("Address of Third Instanse of demo1 is ",demoAddress3); + + const name = await contract.getNameOfContract(demoAddress3); + console.log("Name of given address is " , name); + + +} +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/step03_solidity_tutorial/scripts/Enum/enum.ts b/step03_solidity_tutorial/scripts/Enum/enum.ts new file mode 100644 index 0000000..4fc179d --- /dev/null +++ b/step03_solidity_tutorial/scripts/Enum/enum.ts @@ -0,0 +1,39 @@ +// We require the Hardhat Runtime Environment explicitly here. This is optional +// but useful for running the script in a standalone fashion through `node