Dnes
Building upon the foundations laid in Part 1, this article delves deeper into Ethereum programming. We’ll explore key concepts, practical examples, and advanced techniques for developing decentralized applications (dApps) on the Ethereum blockchain.
Table of contents
Smart Contract Development with Solidity
Solidity remains the primary language for writing smart contracts. Let’s examine some advanced features:
Inheritance
Smart contracts can inherit properties and functions from other contracts, promoting code reuse and modularity.
pragma solidity ^0.8.0;
contract BaseContract {
uint public baseVariable = 10;
function getBaseVariable public view returns (uint) {
return baseVariable;
}
}
contract DerivedContract is BaseContract {
uint public derivedVariable = 20;
function getTotal public view returns (uint) {
return baseVariable + derivedVariable;
}
}
Events
Events allow smart contracts to communicate with the outside world, notifying listeners about state changes.
pragma solidity ^0.8.0;
contract EventExample {
event ValueChanged(uint oldValue, uint newValue);
uint public value;
function setValue(uint _newValue) public {
emit ValueChanged(value, _newValue);
value = _newValue;
}}
Mappings
Mappings are key-value stores, ideal for managing user data or other dynamic information.
pragma solidity ^0.8.0;
contract MappingExample {
mapping(address => uint) public balances;
function deposit public payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint _amount) public {
require(balances[msg.sender] >= _amount, "Insufficient balance");
payable(msg.sender).transfer(_amount);
balances[msg.sender] -= _amount;
}
}
Advanced Web3 Development
Beyond basic smart contract functionality, Ethereum programming involves integrating with web3 libraries and frameworks.
Web3.js
Web3.js allows JavaScript applications to interact with the Ethereum blockchain. It can be used to deploy contracts, call functions, and listen for events.
Ethers.js
Ethers.js is an alternative to Web3.js, offering a more modern and streamlined API.
Security Considerations
Smart contract security is paramount. Common vulnerabilities include:
- Reentrancy attacks
- Integer overflow/underflow
- Denial of service
Auditing your code is crucial.
