Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Solidity

Learn Solidity - 10 Code Examples & CST Typing Practice Test

Solidity is a statically typed, contract-oriented programming language designed for building smart contracts on the Ethereum blockchain. It enables developers to write decentralized applications (dApps), manage digital assets, and automate trustless logic using a syntax inspired by JavaScript, C++, and Python.

View all 10 Solidity code examples →
Solidity Counter ContractSolidity Simple AdditionSolidity FactorialSolidity Fibonacci SequenceSolidity Max of Two NumbersSolidity Array SumSolidity Even Numbers FilterSolidity String ConcatenationSolidity Counter With Loop SimulationSolidity Conditional Increment

Learn SOLIDITY with Real Code Examples

Updated Nov 19, 2025

Explain

Solidity compiles to EVM bytecode and runs on Ethereum nodes.

It powers smart contracts that govern DeFi, NFTs, DAOs, identity systems, and decentralized automation.

Supports inheritance, modifiers, events, libraries, interfaces, and blockchain-specific features like address types and payable functions.

Core Features

Contracts, interfaces, abstract contracts

Mappings, structs, arrays

Events & logs

Fallback & receive functions

Error handling: require, revert, assert

Basic Concepts Overview

Contracts & state variables

Functions (public, private, external)

Mappings, arrays, structs

Modifiers & events

ABI encoding & gas

Project Structure

contracts/

scripts/

test/

deploy/

artifacts/build-info/

Building Workflow

Write Solidity contract in .sol file

Compile with Solidity compiler (solc)

Deploy using Hardhat/Foundry/Truffle

Test using Mocha/Chai or Foundry tests

Interact via scripts or dApp front-end

Difficulty Use Cases

Beginner: ERC-20 token, simple storage contract

Intermediate: NFT collections, staking rewards

Advanced: DEX, lending pools, multi-sig wallets

Expert: zk-integrated contracts, MEV-resistant systems

Comparisons

Solidity vs Rust (Solana): EVM vs non-EVM

Solidity vs Vyper: syntax & security differences

Solidity vs Move (Sui/Aptos): resource model

Solidity vs JavaScript: on-chain vs off-chain logic

Solidity vs Python: static vs dynamic

Versioning Timeline

2014 - Solidity introduced

2016 - Major updates, inheritance

2018 - ABIEncoderV2

2021 - Custom errors

2023-2025 - Optimizer improvements & language hardening

Glossary

EVM: Ethereum Virtual Machine

ABI: Application Binary Interface

Gas: execution cost

Address: 20-byte account identifier

Event: logged blockchain data

Installation Setup

Install Node.js

Install Hardhat or Foundry

Install MetaMask or similar wallet

Set up a local Ethereum node (via Hardhat, Ganache, or Anvil)

Write and compile Solidity contracts

Environment Setup

Install Hardhat or Foundry

Create project directory

Configure networks & private keys

Write contract

Compile & deploy

Config Files

hardhat.config.js

foundry.toml

truffle-config.js

package.json

.env

Cli Commands

npx hardhat compile

npx hardhat test

forge build

forge test

npx hardhat run scripts/deploy.js

Internationalization

Solidity supports UTF-8 strings

Smart contracts are language agnostic

UI translations handled off-chain

Multi-language documentation available

Blockchain-readable formats universal

Accessibility

Remix for beginners

Debug traces & logs

Hardhat console

Solidity documentation

Contract verification explorers

Ui Styling

Solidity does not handle UI

Used via Web3.js/Ethers.js front-ends

Data displayed through dApps

Smart contracts act as backend

UI handled entirely off-chain

State Management

State variables stored on-chain

Mappings manage balances

Events for off-chain syncing

Immutables reduce gas

Storage slots for proxy patterns

Data Management

Structs & arrays

ABI encoding/decoding

Calldata vs memory vs storage

Event logs

Oracles for external data

Architecture

Compiles to Ethereum Virtual Machine bytecode

Smart contracts deployed to blockchain storage

Execution triggered by transactions or calls

State changes stored on-chain

Gas model governs computation & storage

Rendering Model

Solidity code -> solc compiler

Bytecode deployed to blockchain

Executed by EVM

State written to on-chain storage

Transactions trigger contract functions

Architectural Patterns

Factory pattern

Proxy/upgradable pattern

Ownable & role-based access

Pull-payment pattern

Reentrancy-safe design

Real World Architectures

DEXs & AMMs

Lending protocols

NFT marketplaces

Gaming smart contracts

Enterprise Ethereum chains

Design Principles

Deterministic execution

Transparent and immutable logic

Gas-efficient patterns

Security-focused architecture

Contract modularity

Scalability Guide

Use Layer 2 deployments

Batch operations

Reduce storage writes

Use events instead of state

Modularize & split logic

Migration Guide

Refactor old Solidity <0.6 contracts

Update to new error handling

Move to proxy pattern for upgrades

Optimize gas-heavy storage logic

Replace deprecated syntax

Performance Notes

Minimize storage writes

Use events instead of storing historical data

Use immutable/constant variables

Avoid loops over dynamic arrays

Use efficient data structures

Security Notes

Prevent reentrancy with checks-effects-interactions or ReentrancyGuard

Validate user inputs

Use SafeERC20 for token transfers

Implement circuit breakers

Use OpenZeppelin audited libraries

Monitoring Analytics

Tenderly

Etherscan Gas Profiler

Hardhat traces

Block explorers

Event logs & dashboards

Code Quality

Use linters (solhint)

Follow OpenZeppelin standards

Avoid repeated logic

Document storage layouts

Audit code regularly

Practical Examples

Create ERC-20 token

Deploy NFT contract

Build a decentralized marketplace

Create DAO governance contract

Develop DeFi staking protocol

Troubleshooting

Check for reentrancy vulnerabilities

Verify require conditions

Ensure correct visibility specifiers

Check gas usage & optimize loops

Study transaction traces for failed calls

Testing Guide

Write unit tests using Hardhat/Foundry

Test edge cases & error paths

Simulate multi-account interactions

Test reentrancy & exploit conditions

Run gas reports

Deployment Options

Ethereum mainnet

Ethereum testnets (Sepolia, Holesky)

Layer 2 rollups (Arbitrum, Optimism, Base)

Sidechains (Polygon)

Private EVM chains

Tools Ecosystem

Hardhat

Foundry

Truffle

OpenZeppelin Contracts

Remix IDE

Integrations

Web3.js & Ethers.js

IPFS & Filecoin

The Graph indexing

Chainlink oracles

Layer-2 networks

Productivity Tips

Use Hardhat tasks

Automate tests

Use OpenZeppelin templates

Rely on security checkers

Reuse battle-tested libraries

Challenges

Create ERC-20 token

Build NFT smart contract

Create DAO voting mechanism

Make yield farming rewards contract

Build full DeFi protocol component

Learning Path

Learn Ethereum basics

Understand smart contract structure

Master storage, ABI, and gas

Build DeFi/NFT prototypes

Learn contract security & audits

Skill Improvement Plan

Week 1: Syntax, variables, functions

Week 2: Mappings, structs, modifiers, events

Week 3: ERC standards & DeFi patterns

Week 4: Gas optimization & security

Interview Questions

Explain how storage vs memory works.

Difference between view and pure?

What is reentrancy and how do you prevent it?

How does delegatecall work?

Explain the Checks-Effects-Interactions pattern.

Cheat Sheet

uint public x;

mapping(address => uint) balances;

require(condition, 'Error');

emit EventName(param);

transfer, send, call for ETH transfers

Books

Mastering Ethereum

Building Ethereum DApps

Ethereum Smart Contract Development

Tutorials

CryptoZombies

OpenZeppelin Learn

Hardhat tutorials

Patrick Collins Web3 Course

Official Docs

Solidity Documentation

Ethereum Yellow Paper

EVM Opcodes Reference

Community Links

Ethereum StackExchange

Solidity GitHub discussions

ETHGlobal Community

Community Support

Ethereum StackExchange

Discord: Solidity, Hardhat, Foundry servers

OpenZeppelin Community

ETHGlobal hackathons

Reddit r/ethdev

Monetization

Smart contract auditing

DeFi protocol development

NFT marketplace engineering

Blockchain freelancing

Enterprise blockchain consulting

Future Roadmap

Better gas optimization

Safer language features

Improved upgradable contract support

More compiler speed improvements

Wider multi-chain adoption

When Not To Use

Off-chain computation

High-storage applications

Real-time processing

Complex data analytics

Systems needing mutable logic

Final Summary

Solidity is the core language for Ethereum smart contracts.

Used for DeFi, NFTs, DAOs, and enterprise blockchain automation.

Requires strong focus on gas efficiency and security.

Ecosystem-rich and essential for Web3 developers.

Faq

Is Solidity only for Ethereum?

No - it works on all EVM-compatible chains.

Is Solidity hard to learn?

Moderate - but security makes it challenging.

How do I debug smart contracts?

Using Hardhat console, traces, and tests.

Is Solidity secure?

Yes if coded & audited properly; otherwise risky.

Code Sample Descriptions

1

Solidity Counter Contract

pragma solidity ^0.8.0;

contract Counter {
    uint public count = 0;
    bool public isDark = false;

    function increment() public {
        count++;
    }

    function decrement() public {
        count--;
    }

    function reset() public {
        count = 0;
    }

    function toggleTheme() public {
        isDark = !isDark;
    }

    function getUI() public view returns (uint, bool) {
        return (count, isDark);
    }
}

Demonstrates a simple counter smart contract with theme toggle functionality simulated as a boolean.

Let’s Try →
2

Solidity Simple Addition

pragma solidity ^0.8.0;

contract AddProgram {
    uint public a = 5;
    uint public b = 3;
    uint public sum;

    function calculate() public {
        sum = a + b;
    }
}

Adds two numbers and stores the result in a state variable.

Let’s Try →
3

Solidity Factorial

pragma solidity ^0.8.0;

contract Factorial {
    uint public n = 5;
    uint public fact = 1;

    function calculate() public {
        fact = 1;
        for(uint i=1;i<=n;i++) {
        fact *= i;
        }
    }
}

Calculates factorial of a number using a loop.

Let’s Try →
4

Solidity Fibonacci Sequence

pragma solidity ^0.8.0;

contract Fibonacci {
    uint[10] public fib;

    function generate() public {
        fib[0] = 0;
        fib[1] = 1;
        for(uint i=2;i<10;i++) {
        fib[i] = fib[i-1] + fib[i-2];
        }
    }
}

Generates first 10 Fibonacci numbers stored in an array.

Let’s Try →
5

Solidity Max of Two Numbers

pragma solidity ^0.8.0;

contract MaxProgram {
    uint public a = 7;
    uint public b = 10;
    uint public max;

    function findMax() public {
        max = a > b ? a : b;
    }
}

Finds the maximum of two numbers.

Let’s Try →
6

Solidity Array Sum

pragma solidity ^0.8.0;

contract ArraySum {
    uint[5] public nums = [1,2,3,4,5];
    uint public sum;

    function calculateSum() public {
        sum = 0;
        for(uint i=0;i<nums.length;i++) {
        sum += nums[i];
        }
    }
}

Sums elements of an array and stores in a state variable.

Let’s Try →
7

Solidity Even Numbers Filter

pragma solidity ^0.8.0;

contract EvenNumbers {
    uint[10] public nums = [1,2,3,4,5,6,7,8,9,10];
    uint[] public evens;

    function filter() public {
        delete evens;
        for(uint i=0;i<nums.length;i++) {
        if(nums[i] % 2 == 0) {
        evens.push(nums[i]);
        }
        }
    }
}

Returns even numbers from an array.

Let’s Try →
8

Solidity String Concatenation

pragma solidity ^0.8.0;

contract ConcatStrings {
    string public str1 = 'HELLO';
    string public str2 = 'WORLD';
    string public result;

    function concat() public {
        result = string(abi.encodePacked(str1, str2));
    }
}

Concatenates two strings and stores in a state variable.

Let’s Try →
9

Solidity Counter With Loop Simulation

pragma solidity ^0.8.0;

contract LoopCounter {
    uint public count;

    function run() public {
        count = 1;
        while(count <= 5) {
        count++;
        }
    }
}

Counts from 1 to 5 using a loop and stores the final count.

Let’s Try →
10

Solidity Conditional Increment

pragma solidity ^0.8.0;

contract ConditionalIncrement {
    uint public count = 3;

    function run() public {
        if(count < 5) {
        count++;
        }
    }
}

Increment counter only if it is less than 5.

Let’s Try →

Frequently Asked Questions about Solidity

What is Solidity?

Solidity is a statically typed, contract-oriented programming language designed for building smart contracts on the Ethereum blockchain. It enables developers to write decentralized applications (dApps), manage digital assets, and automate trustless logic using a syntax inspired by JavaScript, C++, and Python.

What are the primary use cases for Solidity?

Smart contract development. DeFi protocols (DEXs, lending, staking). NFT standards (ERC-721, ERC-1155). Token creation (ERC-20). DAO governance mechanisms. Permissioned enterprise blockchain apps

What are the strengths of Solidity?

Native support for Ethereum standards. Large community & ecosystem. Powerful for financial logic. Extensive tooling (Hardhat, Foundry, Truffle). Rich developer resources

What are the limitations of Solidity?

Security vulnerabilities are common. Gas-cost constraints. Upgradability complexity. Difficult debugging across chains. Blockchain immutability adds risk

How can I practice Solidity typing speed?

CodeSpeedTest offers 10+ real Solidity code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.