Solidity Basics
Solidity Basic Syntax Notes
1. File Structure
Every Solidity file should start with a license identifier and the pragma version.
1 | // SPDX-License-Identifier: MIT |
2. Contract Structure
A contract is similar to a class in object-oriented languages.
1 | contract MyContract { |
3. Data Types
Value Types
- boolean:
bool public isActive = true; - uint: Unsigned integer (positive only).
uint256is the standard. - int: Signed integer (positive and negative).
- address: Holds a 20-byte Ethereum address.
address public owner;address payable public recipient;(can receive Ether)
Reference Types
- string:
string public name = "Solidity"; - struct: Custom defined types.
1
2
3
4struct User {
uint id;
string name;
} - mapping: Key-value pairs (hash tables).
mapping(address => uint) public balances;
- Arrays:
uint[] public dynamicArray;uint[5] public fixedArray;
4. Functions
Syntax
1 | function functionName(uint _param) public view returns (uint) { |
Visibility Modifiers
- public: Can be called internally and externally.
- private: Only accessible within the current contract.
- internal: Accessible within the contract and derived contracts (inheritance).
- external: Can only be called from outside the contract.
State Modifiers
- view: Promises not to modify the state (reads data only).
- pure: Promises not to modify or read from the state (calculates logic only).
- payable: Allows the function to receive Ether.
5. Data Locations
Where data is stored during execution:
- storage: Persistent on-chain storage (state variables).
- memory: Temporary storage (exists only during function execution).
- calldata: Non-modifiable temporary storage for function arguments.
6. Control Structures
Solidity uses standard C-style syntax.
1 | // If-Else |
7. Error Handling
- require(condition, “error message”): Reverts if condition is false. Used for input validation.
- revert(“error message”): Aborts execution and reverts changes.
- assert(condition): Used for internal invariants (serious bugs).
8. Events
Events allow logging to the Ethereum blockchain, which off-chain applications can listen for.
1 | event Transfer(address indexed from, address indexed to, uint amount); |
9. Global Variables
msg.sender: Address of the person calling the function.msg.value: Amount of Wei sent with the call.block.timestamp: Current block timestamp.block.number: Current block number.
评论



