




































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
A detailed guide on ethereum smart contract development, covering topics such as frontend and backend development, blockchain, bitcoin, ethereum, smart contracts, chainlink, ethereum transactions, wallet creation, gas fees, consensus mechanisms, solidity, remix ide, storage, arrays, inheritance, and more. It also discusses the importance of ethereum, chainlink features, advantages of smart contracts and blockchain, decentralized applications (daos), and security aspects.
Typology: Schemes and Mind Maps
1 / 44
This page cannot be seen from the preview
Don't miss anything!
5.1.1 Uniswap april 2020 .................................................................................................................. 35 5.1.2 Defi Pie Hack on Binance Smart Chain .................................................................................... 38 5.2 Popsicle Finance bug ....................................................................................................................... 43
6 Openzeppelin...................................................................................... Errore. Il segnalibro non è definito.
7 Metamask ........................................................................................... Errore. Il segnalibro non è definito.
7.1 MetaMask: a different model of account security ..................... Errore. Il segnalibro non è definito. 7.1.1 Intro to Secret Recovery Phrases ....................................... Errore. Il segnalibro non è definito. 7.1.2 There are a number of important features to note here: .. Errore. Il segnalibro non è definito. 7.1.3 MetaMask Secret Recovery Phrase: DOs and DON'Ts ....... Errore. Il segnalibro non è definito.
8 Remix .................................................................................................. Errore. Il segnalibro non è definito.
9 Blockchains and tokens ........................................................................................................................... 22
9.1 Tokens.............................................................................................................................................. 23 9.1.1 ERC-20 token standards........................................................................................................... 23 9.1.2 ERC-721: Non- fungible tokens ................................................................................................ 24 9.1.3 ERC-1155: Multi-token Standard ............................................................................................. 25 9.1.4 ERC- 777 .................................................................................................................................... 25 9.2 How does the interface of ERC-20, ERC-721, and ERC-1155 look like? ......................................... 26 9.2.1 ERC- 20 ...................................................................................................................................... 26 9.2.2 ERC- 721 .................................................................................................................................... 28 9.2.3 ERC- 1155 .................................................................................................................................. 29
10 Frontend interfaces ........................................................................ Errore. Il segnalibro non è definito.
10.1 Creating a React project and directory structure ....................... Errore. Il segnalibro non è definito. 10.2 React with Vite ........................................................................... Errore. Il segnalibro non è definito. 10.3 Component Directory ................................................................. Errore. Il segnalibro non è definito. 10.4 Unit Tests .................................................................................... Errore. Il segnalibro non è definito. 10.5 Index Page .................................................................................. Errore. Il segnalibro non è definito. 10.6 Ejecting ....................................................................................... Errore. Il segnalibro non è definito. 10.7 Building, debugging, running the project ................................... Errore. Il segnalibro non è definito. 10.8 Connecting Metamask Wallet .................................................... Errore. Il segnalibro non è definito. 10.9 Web3.js ....................................................................................... Errore. Il segnalibro non è definito. 10.9.1 Building a transaction ......................................................... Errore. Il segnalibro non è definito. 10.9.2 Deploying Smart Contracts ................................................. Errore. Il segnalibro non è definito. 10.9.3 Calling Smart Contract Functions with Web3.js ................. Errore. Il segnalibro non è definito. 10.9.4 Smart Contract Events with Web3.js .................................. Errore. Il segnalibro non è definito. 10.9.5 Inspecting Blocks with Web3.js .......................................... Errore. Il segnalibro non è definito. 10.9.6 Web3.js Utilities.................................................................. Errore. Il segnalibro non è definito.
17.1 Uniswap version 1 ...................................................................... Errore. Il segnalibro non è definito. 17.1.1 Order Books ........................................................................ Errore. Il segnalibro non è definito. 17.1.2 Automated Market Makers ................................................ Errore. Il segnalibro non è definito. 17.1.3 Being a liquidity provider.................................................... Errore. Il segnalibro non è definito. 17.1.4 Impermanent loss ............................................................... Errore. Il segnalibro non è definito. 17.2 A staking Dapp ............................................................................ Errore. Il segnalibro non è definito. 17.3 Dapp Token................................................................................. Errore. Il segnalibro non è definito. 17.4 Token farm.................................................................................. Errore. Il segnalibro non è definito.
18 Tools ............................................................................................... Errore. Il segnalibro non è definito.
18.1 New developers start here ......................................................... Errore. Il segnalibro non è definito. 18.1.1 Developing Smart Contracts ............................................... Errore. Il segnalibro non è definito. 18.1.2 Other tools .......................................................................... Errore. Il segnalibro non è definito. 18.1.3 Test Blockchain Networks .................................................. Errore. Il segnalibro non è definito. 18.1.4 Communicating with Ethereum.......................................... Errore. Il segnalibro non è definito. 18.1.5 Infrastructure...................................................................... Errore. Il segnalibro non è definito. 18.1.6 Testing Tools ....................................................................... Errore. Il segnalibro non è definito. 18.1.7 Security Tools...................................................................... Errore. Il segnalibro non è definito. 18.1.8 Monitoring .......................................................................... Errore. Il segnalibro non è definito. 18.1.9 Other Miscellaneous Tools ................................................. Errore. Il segnalibro non è definito. 18.1.10 Smart Contract Standards & Libraries ............................ Errore. Il segnalibro non è definito. 18.1.11 Developer Guides for 2nd Layer Infrastructure.............. Errore. Il segnalibro non è definito.
To become a blockchain developer, you shouldn’t only learn programming a few languages and frameworks, but also how things work ‘under the hood’. It’s a long journey if you really want to learn all the details. Many tools and technologies can be found here:
https://github.com/ConsenSys/ethereum-developer-tools-list
As for ‘legacy’ web 2.0 developers, usually there is a distinction between the following:
‘ Full stack ’ developers are able to write everything on their own, of course everyone claims to be an experienced full stack developer because companies always look for them to save one more person and its gross salary, but REAL experienced full stack developers are rare. They are two DIFFERENT career paths each of them probably requiring YEARS of experience. As usual, companies ask for more and more tech knowledge, without understanding that it’s simply impossible to know a variety of stuff that spans multiple tech areas, where you need YEARS to become an expert. Luckily there are no barriers for tech, you don’t need a computer science degree to start programming, leaning AI, working on blockchain and developing a smart contract, becoming a network engineer or a security engineer, a Cybersecurity expert or an IOT expert. Also do not believe to all those video ‘clone the internet in 2 minutes’, ‘reinvent Ethereum in 10 seconds’, ‘create an NFT marketplace in 30 minutes’, usually they are just titles to have more people watching the videos and increase their gains. At the same time, don’t feel stupid if you think you can’t learn and do everything in 10 minutes, and as the time passes by you feel like the Iceberg is quite big below the water’s surface: real tech professionals already know it’s BULLSHIT.
The effort and work in the last years around the blockchain space has been terrific, so many tools are out there to make your life easier and develop better and faster. Security is still a concern, since many hacks still happen and will continue to happen. Even stupid ones, like someone modifying the official library for NFT provided by OpenZeppelin, so that the call to transfer the owner of an NFT can be performed by anyone, or by other people different from the owner (like for example the contract’s issuer). This will continue to happen until more secure standards will be in place.
For example, as far as I know only the bytecode is stored in the blockchain, not the source code that generated it. There should be a way to reverse the process, so that if you wish, you can check what the code in the blockchain really does, and what is the source code that has generated it. I was shocked in 2002 when I discovered that someone could reverse engineer a Java bytecode (that machine independent middle ‘stratum’), thus providing back the source code, even though Java claimed it was virtually impossible. Well, it looks like it’s also possible with Solidity bytecode, even though it requires time.
has produced this 16 hours long video, with a lot of Python content. You don’t need to copy and paste everything from the video, even though you could learn more in this way, at least in the beginning. Most if not all the source code is available on github and thus you can locally clone it with one single command. In general FreeCodeCamp contains a lot of free resources about programming languages, and they are averagely speaking FREE and very well done. Of course, just watching them is not enough. 16 hours is not enough to become a ‘from zero to hero’ blockchain developer. It’s a hard path understanding all the details, but you need to start somewhere.
https://www.youtube.com/watch?v=M576WGiDBdQ&t=12013s
00:00:00 - Introduction 00:00:51 - Author 00:02:04 - prerequisites 00:03:00 - Resources 00:03:57 - learn at your own Pace 00:05:00 - Community 00:05:58 - Blockchain 00:06:25 - Bitcoin 00:07:27 - Ethereum 00:08:14 - Smart Contracts 00:09:07 - Bitcoin vs Ethereum 00:09:43 - Oracle problem & Solution 00:10:28 - Hybrid Smart Contracts 00:11:01 - Chainlink 00:12:47 - Importance of Ethereum 00:13:33 - Chainlink features 00:13:50 - summary 00:15:04 - Features & Advantages of Smart contracts and Blockchain 0 0:15:15 - Decentralized 00:16:55 - Transparency & Flexibility 00:17:35 - Speed & Efficiency 00:18:11 - Security & Immutability 00:19:34 - Removal of Counterparty risks 00:21:13 - Trust Minimized Agreements 00:23:21 - Summary 00:24:46 - DAOs 00:25:15 - Ethereum Transaction On a Live Blockchain 00:25:57 - Wallet Creation 00:29:30 - Etherscan 00:30:03 - Multiple Accounts 00:30:28 - Mnemonic , Public & Private keys 00:31:34 - Mnemonic vs Private vs Public keys 00:32:02 - Mainnet & Testnets 00:33:39 - Initiating our first Transaction 00:35:55 - Transaction details 00:36:50 - Gas fees, Transaction fees, Gas limit, Gas price .... 00:39:36 - Gas vs Gas price vs Gas Limit vs Transaction fee 00:40:40 - Gas estimator 00:43:46 - How Blockchain works/whats going on Inside the Blockchain 00:44:26 - Hash or Hashing or SHA 00:46:35 - Block 00:49:37 - Blockchain 00:53:18 - Decentralized/Distributed Blockchain 00:57:19 - Tokens/Transaction History 00:59:55 - Recap/summary 01:01:34 - Signing and Verifying a Transaction 01:01:45 - Public & Private Keys 01:03:29 - Signatures 01:05:05 - Transactions 01:07:39 - Recap/summary 01:09:00 - Concepts are same 01:10:03 - Nodes 01:10:40 - Anyone can Become a Node 01:11:02 - Centralized entity vs Decentralized Blockchain 01:11:55 - Transactions are Listed 01:12:27 - Consensus ,Proof of Work ,Proof of Stake
01:12:35 - Consensus 01:13:21 - proof of work/Sybil resistance mechanism 01:14:56 - Blocktime 01:15:32 - Chain selection rule 01:15:50 - Nakamoto consensus 01:16:15 - Block Confirmations 01:17:00 - Block rewards & transaction fees 01:19:34 - Sybil attack 01:19:52 - 51% attack 01:21:41 - Drawbacks of pow 01:21:53 - proof of stake/sybil resistance mechanism 01:23:14 - Validators 01:24:27 - pros & cons of pos 01:25:27 - Scalability problem & Sharding solution 01:26:40 - Layer 1 & Layer 2 01:27:22 - Rollups 01:28:15 - Recap/Summary 01:29:28 - Solidity 01:30:47 - Lesson 1 - Remix IDE & its features 01:33:32 - Solidity version 01:35:29 - Defining a Contract 01:36:08 - Variable types & Declaration 01:38:45 - Solidity Documentation 01:39:01 - Initializing 01:39:55 - Functions or methods 01:40:54 - Deploying a Contract 01:42:05 - Public , Internal , private , External Visibility 01:44:54 - Modifying a Variable 01:45:49 - Scope 01:47:10 - View functions 01:48:51 - Pure function 01:50:57 - Structs 01:52:42 - Intro to storage 01:53:22 - Arrays 01:54:27 - Dynamic array 01:54:41 - Fixed array 01:54:54 - Adding to an array 01:56:12 - Compiler Errors 01:57:27 - Memory Keyword 01:57:48 - Storage keyword 01:59:44 - Mappings Datastructure 02:01:53 - SPDX license 02:02:37 - Deploying to a live network 02:06:16 - Interacting with deployed contracts 02:07:35 - EVM 02:08:31 - Recap/summary 02:09:20 - Lesson 2 - StorageFactory 02:09: 44 - Factory pattern 02:10:21 - New contract StorageFactory 02:11:36 - Import 1 contract into another 02:13:01 - Deploy a Contract from a Contract 02:14:43 - Track simple storage contracts 02:16:34 - Interacting with Contract deployed Contract 02:16:43 - Calling Store & Retrieve Functions from SF 02:17:43 - Address & ABI 02:19:15 - Compiling & storing in SS through SF 02:20:00 - Adding Retrieve Function 02:21:50 - Compiling 02:22:27 - Making the Code lil bit Simpler 02:23:32 - Additional Note 02:23:58 - Inheritance 02:25:53 - Recap 02:26:23 - Lesson 3 - Fund me 02:27:12 - purpose of this contract 02:27:21 - Payable function , wei , gwei & ether 02:28:30 - Mapping , msg. sender , msg.value 02:30:23 - Funding 02:31:48 - ETH - > USD /conversion 02:32:38 - Deterministic problem & Oracle solution 02:34:15 - Centralized Oracles
03:54:23 - Connecting to Ganache(RPC server,Documentation,Chain ID,address,Privatekey) 03:56:14 - Deploy to Ganache 03:57:03 - Building a Transaction 03:57:22 - Nonce 03:58:14 - Getting Nonce 03:59:00 - Create a Transaction 03:59:42 - Transaction Parameters 04:00:55 - Signing Our Transaction(signed_txn) 04:01:52 - Never Hardcode your Private keys 04:02:09 - Environment Variables 04:02:27 - Setting Environment variables 04:03:00 - Limitations of Exporting Environment Variables 04:03:27 - Private key PSA 04:03:53 - Accessing Environment Variables 04:04:20 - .env file, .gitignore, pip install python-dotenv 04:05:49 - load_dotenv() 04:07:03 - Sending the signed Transaction 04:07:47 - Deployment 04:08:31 - Block confirmation(wait_for_transaction_reciept) 04:09:05 - interact/work with thee contract 04:09:27 - Address & ABI 04:10:28 - Retrieve() , Call & Transact 04:12:38 - Store function 04:13:58 - Creating Transaction(Store_transaction) 04:15:14 - Signing Transaction(signed_store_txn) 04:15:42 - Sending Transaction(send_store_tx,tx_receipt) 04:16:47 - Deployment 04:17:42 - some nice syntax & deployment 04:18:48 - ganache-cli 04:19:10 - install Nodejs 04:19:40 - install yarn 04:20:38 - Run ganache cli , ganache documentation 04:21:44 - update privatekeys,addresses,http provider 04:22:13 - open new terminal & deploy 04:23:00 - deploy to testnet/mainnet 04:23:55 - Infura, Alchemy 04:24:34 - Create project 04:25:05 - update the rinkeby url, Chain id , address & private key 04:26:20 - Deploying 04:27:21 - summary/recap 04:27:40 - Lesson 5 - Brownie Simple Storage 04:27:53 - Brownie Intro & Features 04:28:44 - create new directory 04:29:39 - install Brownie 04:30:41 - 1st brownie simplestorage project 04:31:08 - Brownie Folders 04:32:25 - copying simplestorage.sol 04:32:44 - brownie compile & store 04:33:22 - brownie deploy 04:33:44 - brownie commands 04:34:22 - brownie runscripts/deploy. py & default brownie network 04:35:10 - brownie Advantages over web3. py in deploying 04:35:38 - getting address & private key using Accounts package 04:36:00 - add default ganache account using index 04:36:58 - add accounts using Commandline 04:37:50 - remove accounts & terminal tips 04:38:17 - getting freecodecamp-account 04:39:15 - add accounts using env variables 04:40:01 - create .env file , brownie-config. yaml 04:40:51 - getting. env 04:41:17 - adding wallets in yaml file and updating in account 04:42:47 - importing contract simplestorage 04:43:09 - importing & deploying in brownie vs web3. py 04:44:27 - running 04:44:46 - recreating web3 .py script in brownie 04:46:20 - running 04:46:48 - tests 04:47:43 - test SS
The above index has been copied from the comments to the video. The shortest summary is the following:
⌨️ (00:00:00) Introduction ⌨️ (00:06:33) Lesson 0: Welcome To Blockchain ⌨️ (01:31:00) Lesson 1: Welcome to Remix! Simple Storage ⌨️ (02:09:32) Lesson 2: Storage Factory ⌨️ (02:26:35) Lesson 3: Fund Me ⌨️ (03:26:48) Lesson 4: Web3.py Simple Storage ⌨️ (04:27:55) Lesson 5: Brownie Simple Storage ⌨️ (05:06:34) Lesson 6: Brownie Fund Me ⌨️ (06:11:38) Lesson 7: SmartContract Lottery ⌨️ (08:21:02) Lesson 8: Chainlink Mix ⌨️ (08:23:25) Lesson 9: ERC20s, EIPs, and Token Standards ⌨️ (08:34:53) Lesson 10: Defi & Aave ⌨️ (09:50:20) Lesson 11: NFTs ⌨️ (11:49:15) Lesson 12: Upgrades ⌨️ (12:48:06) Lesson 13: Full Stack Defi ⌨️ (16:14:16) Closing and Summary
Another great source is the following one: https://www.youtube.com/c/DappUniversity/community ... in this case Javascript, Web3.js and Truffle are used to build the apps (no Python).
For Brownie and Python applied to ‘Curve’ Defi and DAO project, watch the following video series: https://www.youtube.com/watch?v=nkvIFE2QVp0&list=PLVOHzVzbg7bFUaOGwN0NOgkTItUAVyBBQ&inde x=
The most complete resource for detailed documentation and learning is the official one:
https://docs.soliditylang.org/en/v0.8.12/
... where you can find tons of ‘learn by examples’ too. A simple example smart contract:
contract Example{ function(uint256) returns (uint256) varName; function simpleFunction(uint256 parameter) returns (uint256){ return parameter; } function test(){ varName = simpleFunction; } }
The learning curve if you already know Java, C++ or others (object oriented programming languages), is absolutely not high. Some important notes about Solidity:
view can be considered as the subset of constant that will read the storage (hence viewing). However the storage will not be modified. If you use such functions, you’re not gonna pay any gas for it, but the EVM could stop you if your queries become too long.
contract viewExample {
string state; // other contract functions function viewState() public view returns(string) { //read the contract storage return state; } }
pure can be considered as the subset of constant where the return value will only be determined by it's parameters (input values). There will be no read or write to storage and only local variable will be used (has the concept of pure functions in functional programming).
contract pureExample { // other contract functions function pureComputation(uint para1 , uint para2) public pure returns(uint result) { // do whatever with para1 and para2 and assign to result as below result = para1 + para2; return result; } }
https://docs.soliditylang.org/en/develop/units-and-global-variables.html?highlight=msg.value#block-and- transaction-properties Follow hereafter the ‘embedded’ state variables that can always be accessed from inside a contract. They are passed by the system itself, thus they depend on Ethereum and could be different from chain to chain (for example Avalanche, Binance Chain, Solana, ...).
the 256 most recent blocks; otherwise returns zero
The following parameters are contract related:
are given in parentheses as second argument. Example: (uint a, uint[2] memory b, bytes memory c) = abi.decode(data, (uint, uint[2], bytes))
Note that packed encoding can be ambiguous!
arguments starting from the second and prepends the given four-byte selector
to abi.encodeWithSelector(bytes4(keccak256(bytes(signature))), ...)
to functionPointer with the arguments found in the tuple. Performs a full type-check, ensuring the types match the function signature. Result equals abi.encodeWithSelector(functionPointer.selector, (...))
Storage and Memory keywords in Solidity are analogous to Computer’s hard drive and Computer’s RAM. Much like RAM, Memory in Solidity is a temporary place to store data whereas Storage holds data between function calls. The Solidity Smart Contract can use any amount of memory during the execution but once the execution stops, the Memory is completely wiped off for the next execution. Whereas Storage on the other hand is persistent, each execution of the Smart contract has access to the data previously stored on the storage area. Every transaction on Ethereum Virtual Machine costs us some amount of Gas. The lower the Gas consumption the better is your Solidity code. The Gas consumption of Memory is not very significant as compared to the gas consumption of Storage. Therefore, it is always better to use Memory for intermediate calculations and store the final result in Storage.
modifier costs(uint price) { if (msg.value >= price) { _; } } }
contract Register is Owner { mapping (address => bool) registeredAddresses; uint price; constructor(uint initialPrice) public { price = initialPrice; } function register() public payable costs(price) { registeredAddresses[msg.sender] = true; } function changePrice(uint _price) public onlyOwner { price = _price; } }
All you need to do is have the selfdestruct(address payable recipient) function. selfdestruct takes a single parameter that sends all ETH in the contract to that address. In your case, you can do:
function finalize() public creatorOnly biddingClosedOnly { selfdestruct (_creator); }
From the docs:
Selfdestruct (address payable recipient):
destroy the current contract, sending its funds to the given address. The reason you can still call the function after the contract has been selfdestructed is because technically the address is still valid. However, no contract (data) lives there any more. Because of this, you can still send ETH to the address and you can still send transactions with data to the address, but the EVM will not execute the function as it would with a non-selfdestructed address.
Edit: You can use the get_code RPC method to verify that the contract was, in fact, destroyed.
Using ethers.js , the following output will be given:
// Deploy contract
ethersProvider.getCode('0xDCcd6331401b62ebcE7F3a22e966b26ACe27559d').then(console.log)
0x608060405260043610603f576000357c010000000000 0000000000000000000000000000000000000000000 000900463ffffffff1680634bb278f3146044575b600080fd5b348015604f57600080fd5b5060566058565b 5b3373ffffffffffffffffffffffffffffffffffffffff16ff00a165627a7a7230582077ca7684f4d93293e 0c5c695d0e416f54dde89713426cc4d6fddb9f9963faa
// Self destruct contract
ethersProvider.getCode('0xDCcd6331401b62ebcE7F3a22e966b26ACe27559d').then(console.log)
0x
Remix can’t be used by professional developers. Unfortunately, it doesn’t seem there is a classic debugger to analyze how things go step by step, and variables change after every line of command. Many tasks are written and deployed using Python and Web3/Brownie, or Javascript and Web3.js and truffle/hardhat. In any case,
there is no simple way to debug a Solidity Smart Contract line by line. The ‘console’ feature is useful as will be explained when we’ll talk about Brownie.
Events are used to inform external users that something happened on the blockchain. Smart contracts themselves cannot listen to any events. All information in the blockchain is public and any actions can be found by looking into the transactions close enough but events are a shortcut to ease the development of outside systems in cooperation with smart contracts. Solidity defines events with the event keyword. After events are called, their arguments are placed in the blockchain. To use events first, you need to declare them in the following way:
event moneySent(address _from, address _to, uint _amount);
The definition of the event contains the name of the event and the parameters you want to save when you trigger the event. Then you need to emit your event within the function:
emit moneySent(msg.sender, _to, _amount);
Solidity events are interfaces with Ethereum Virtual Machine logging functionality. You can add an attribute indexed to up to three parameters. When parameters do not have the indexed attribute, they are ABI- encoded into the data portion of the log.
Some other debugging tools are the following, to be used off-chain for local testing, excluded the last one:
The convenience functions assert and require can be used to check for conditions and throw an exception if the condition is not met. The assert function creates an error of type Panic(uint256). The same error is created by the compiler in certain situations as listed below. Assert should only be used to test for internal errors, and to check invariants. Properly functioning code should never create a Panic, not even on invalid external input. If this happens, then there is a bug in your contract which you should fix. Language analysis tools can evaluate your contract to identify the conditions and function calls which will cause a Panic.
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"); } }
Fallback functions in Solidity are executed when a function identifier does not match any of the available functions in a smart contract or if there was no data supplied at all. They are unnamed, they can’t accept arguments, they can’t return anything, and there can only ever be one fallback function in a smart contract. In short, they’re a safety valve of sorts. Fallback functions are executed whenever a particular contract receives plain Ether without any other data associated with the transaction. This default design choice makes sense and helps protect users, however, depending on your use case, it may be critical that your smart contract receive plain Ether via a fallback function. To do so the fallback function must include the payable modifier:
contract ExampleContract { function() payable { ... } }
contract will issue an exception and return the Ether to the sender. What if a contract is supposed to do something once Ether is sent to it? The fallback function can only rely on 2300 gas being available. This doesn’t leave much room to perform other operations, particularly expensive ones like writing to storage, creating contracts, calling external functions, and sending Ether.
Inheritance is one of the most important features of the object-oriented programming language. It is a way of extending the functionality of a program, used to separate the code, reduces the dependency, and increases the re-usability of the existing code. Solidity supports inheritance between smart contracts, where multiple contracts can be inherited into a single contract. The contract from which other contracts inherit features is known as a base contract, while the contract which inherits the features is called a derived contract. Simply, they are referred to as parent-child contracts. The scope of inheritance in Solidity is limited to public and internal modifiers only. Some of the key highlights of Solidity are:
Solidity provides different types of inheritance. Functions that can be overriden are defined as ‘virtual’ on the parent class. This is thought to provide more secure implementations.
In Single or single level inheritance the functions and variables of one base contract are inherited to only one derived contract. Example: In the below example, the contract parent is inherited by the contract child, to demonstrate Single Inheritance.
// Solidity program to // demonstrate // Single Inheritance pragma solidity >=0.4.22 <0.6.0;
// Defining contract contract parent{ // Declaring internal // state variable uint internal sum;
// Defining external function // to set value of internal // state variable sum function setValue() external { uint a = 10; uint b = 20; sum = a + b; } }
// Defining child contract contract child is parent{ // Defining external function // to return value of // internal state variable sum function getValue( ) external view returns(uint) { return sum;