Basic Structure of a Solidity Contract
// SPDX-License-Identifier: MITpragma 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 VariablesPermanently stored in contract storage, state variables represent the contract's state.
- FunctionsFunctions are executable units of code within a contract.
- EventsEvents allow logging to the Ethereum blockchain for frontend applications.
Data Types in Solidity
Value Types
- bool: true or false
- int/uint: signed and unsigned integers3.** 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 uint256Prefer uint256 for integers when possible.
- Avoid LoopsMinimize loops to reduce gas consumption.
- Use EventsEmit events instead of storing data.
- Optimize StoragePack variables to save storage slots
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse