✍️ Writing Solidity: Your First Smart Contract Code

Learn basic Solidity syntax for state variables, constructors, and functions

Previous
Introduction

📝 Writing Your First Contract

Let's write a simple smart contract that stores a number on the blockchain. We'll break down every line so you understand what's happening!

🎮 Interactive: Line-by-Line Code Breakdown

Step through the code to understand each part of the contract

Step 1 of 7
License Identifier
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4contract SimpleStorage {
5 uint256 public storedData;
6
7 function set(uint256 x) public {
8 storedData = x;
9 }
10}
// SPDX-License-Identifier: MIT

Specifies the license. MIT is common for open-source. Required by Solidity compiler.

🔍 Key Solidity Concepts

State Variables

Variables stored permanently on blockchain. Cost gas to write, free to read.

uint256 myNumber; // Stored forever
Functions

Code that can be called externally or internally. Can modify state or just read.

function myFunction() public {}
Visibility Modifiers

Control who can access functions and variables.

public: Anyone can call (external or internal)
private: Only this contract
internal: This contract + inherited contracts
external: Only from outside the contract

🎯 What Does This Contract Do?

📥
Store a Number

Call set(42) to store 42 on blockchain

📤
Read the Number

Call storedData() to read current value

Gas Costs

Writing costs ~25,000 gas. Reading is FREE (doesn't modify state)

🌍
Public Data

Anyone can read or write. No access control (for simplicity)

💡 Common Data Types

TypeDescriptionExample
uint256Unsigned integer (0 to 2^256-1)uint256 age = 25;
int256Signed integer (negative allowed)int256 temp = -10;
addressEthereum address (20 bytes)address owner = 0x...
boolBoolean (true/false)bool isActive = true;
stringText (UTF-8 encoded)string name = "Alice";
bytes32Fixed-size byte arraybytes32 hash = 0x...

✏️ Try It Yourself: Remix IDE

Step 1: Open Remix

Go to remix.ethereum.org in your browser

Step 2: Create File

File Explorer → contracts folder → New File → Name it SimpleStorage.sol

Step 3: Paste Code

Copy the SimpleStorage contract code and paste it into your file

Step 4: Save

Ctrl+S (Windows) or Cmd+S (Mac) to save. Remix auto-compiles!

🎓 Pro Tips

💡
Start Simple
Don't try to build complex contracts immediately. Master basics first!
📝
Comment Your Code
Use // for single-line or /* */ for multi-line comments. Explain WHY, not just what.
🔍
Read Other Contracts
Check verified contracts on Etherscan. Learn from production code!
🛡️
Test Everything
Always test on testnet before mainnet. Bugs cost real money on mainnet!