Basic Structure of a Solidity Contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyContract {
// State variables
uint public myNumber;
// Constructor
constructor(uint _num) {
myNumber = _num;
}
// Function to update state variable
function setNumber(uint _num) public {
myNumber = _num;
}
// Function to retrieve state variable
function getNumber() public view returns (uint) {
return myNumber;
}
}
Contract Structure
**Contracts **are the fundamental building blocks in Solidity, similar to classes in object-oriented programming.
- State Variables Permanently stored in contract storage, state variables represent the contract's state.
- Functions Functions are executable units of code within a contract.
- Events Events allow logging to the Ethereum blockchain for frontend applications.
Data Types in Solidity
Value Types
- bool: true or false
- int/uint: signed and unsigned integers 3.** address**: Ethereum address
bytes: dynamic array of bytes
Reference Typesarrays: fixed or dynamic size
struct: custom defined type
mapping: hash tables
Function Visibility and Modifiers
- public - Accessible from anywhere.Can be called internally or via messages. Generates a getter function for state variables.
- private - Only within the contract.Only visible for the contract they are defined in. 3.** internal** - Within the contract and derived contracts.Only accessible internally and by derived contracts.
- *external *- Only callable from outside the contract.Can be called from other contracts and transactions. Cannot be called internally.
Function Modifiers
- pure - No state modifications
- view - Reads state but doesn’t modify it
- payable - Accepts Ether
Gas Optimization Techniques
- Use uint256 Prefer uint256 for integers when possible.
- Avoid Loops Minimize loops to reduce gas consumption.
- Use Events Emit events instead of storing data.
- Optimize Storage Pack variables to save storage slots
Top comments (0)