Knowledge / Computer Science and Engineering / Smart contracts and Solidity

Smart contracts and Solidity

Computer Science and Engineering (B.E./B.Tech) · Blockchain · free study notes for exams, placements and interviews

In short

A smart contract is a program stored on a blockchain whose code and state are replicated on every node, and which executes deterministically when a transaction calls it - "code is the agreement". Solidity is the dominant statically typed, contract-oriented language that compiles to Ethereum Virtual Machine (EVM) bytecode and runs on Ethereum and every EVM-compatible chain (Polygon PoS, BNB Chain, Avalanche, Arbitrum, Polygon zkEVM). University syllabi examine the EVM execution model, gas, Solidity data and control constructs, visibility, modifiers, events, token standards and the classic vulnerabilities; GATE CS has no dedicated blockchain section, but blockchain appears in university electives, UGC-NET computer science and professional certification. Indian employers hiring on this skill include Infosys, TCS, Wipro, Tech Mahindra, Accenture, Cognizant, Polygon Labs, CoinDCX, WazirX, Zebpay, Mudrex and bank innovation units; the RBI's e-rupee pilots and ONDC-adjacent pilots keep demand live. Note that in India crypto-assets are legal to hold and trade but are not legal tender, and token issuance has no dedicated statute yet.

Explained

What a smart contract is, and what it is not

The EVM execution model and gas

Solidity language essentials

Calling, sending value and the standard contract patterns

Token standards and the ecosystem

StandardWhat it isKey interface
ERC-20Fungible tokentotalSupply, balanceOf, transfer, approve, allowance, transferFrom, events Transfer, Approval
ERC-721Non-fungible token (unique IDs)ownerOf, safeTransferFrom, approve, setApprovalForAll, tokenURI
ERC-1155Multi-token (fungible + NFT, batch)balanceOfBatch, safeBatchTransferFrom
ERC-4626Tokenised vault (yield)deposit, mint, withdraw, redeem, convertToShares
ERC-2612Gasless approve by signaturepermit(owner,spender,value,deadline,v,r,s)
ERC-4337Account abstraction (smart accounts, paymasters)EntryPoint, UserOperation

Advantages, limitations and the Indian regulatory frame

Key points

Formulas and examples

Fee (EIP-1559) = gasUsed × (baseFee + priorityFee); result in wei. 1 gwei = 10⁻⁹ ether.
1 ether = 1018 wei; 1 gwei = 109 wei. Fee in ether = fee_wei / 1018.
Token raw amount = humanAmount × 10decimals (uint256, no fractions).
Storage slots used = ceil(Σ variable bytes packed in declaration order / 32).
Function selector = first 4 bytes of keccak256("name(type1,type2)"); calldata size = 4 + 32 × (number of static words).
Simple interest accrued on-chain = principal × rate_bps × elapsedSeconds / (10000 × 365 × 24 × 3600), integer division.

Example 1 - cost of a transfer in rupees. An ERC-20 transfer uses 51,000 gas. baseFee = 18 gwei, priorityFee = 2 gwei, 1 ETH = ₹2,40,000.

Example 2 - token decimals. A rupee-pegged token with 2 decimals must transfer ₹1,250.75.

Example 3 - storage packing and gas saved.

contract Bad { uint256 a; uint8 b; uint256 c; uint8 d; }  // 4 slots
contract Good { uint256 a; uint256 c; uint8 b; uint8 d; } // 3 slots

Example 4 - a complete, safe contract.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract Escrow {
    address public immutable buyer;
    address public immutable seller;
    uint256 public deadline;
    bool public released;
    mapping(address => uint256) public refunds;   // pull-payment ledger

    error NotBuyer();
    error TooEarly(uint256 now_, uint256 deadline_);

    event Deposited(address indexed from, uint256 amount);
    event Released(address indexed to, uint256 amount);

    modifier onlyBuyer() {
        if (msg.sender != buyer) revert NotBuyer();
        _;                                        // function body runs here
    }

    constructor(address seller_, uint256 days_) payable {
        buyer = msg.sender;
        seller = seller_;
        deadline = block.timestamp + days_ * 1 days;
        emit Deposited(msg.sender, msg.value);
    }

    receive() external payable { emit Deposited(msg.sender, msg.value); }

    function release() external onlyBuyer {
        require(!released, "already released");
        released = true;                          // EFFECT before INTERACTION
        uint256 amount = address(this).balance;
        (bool ok, ) = payable(seller).call{value: amount}("");
        require(ok, "transfer failed");
        emit Released(seller, amount);
    }

    function claimRefund() external {
        if (block.timestamp < deadline) revert TooEarly(block.timestamp, deadline);
        uint256 amount = refunds[msg.sender];
        refunds[msg.sender] = 0;                  // zero first
        (bool ok, ) = payable(msg.sender).call{value: amount}("");
        require(ok, "refund failed");
    }
}

Example 5 - the reentrancy bug and its fix.

// VULNERABLE: interaction before effect
function withdraw() external {
    uint256 bal = balances[msg.sender];
    (bool ok, ) = msg.sender.call{value: bal}("");   // attacker re-enters here
    require(ok);
    balances[msg.sender] = 0;                        // too late
}
// FIXED
function withdraw() external nonReentrant {
    uint256 bal = balances[msg.sender];
    balances[msg.sender] = 0;                        // effect first
    (bool ok, ) = msg.sender.call{value: bal}("");
    require(ok, "fail");
}
Concerntransfersendcall{value:}
Gas forwarded2,3002,300all remaining (or specified)
On failurerevertsreturns falsereturns false
Reentrancy risklowlowreal - needs guard
Recommended nowno (stipend may break)noyes, with CEI + guard
calldelegatecallstaticcall
Code runcallee'scallee'scallee's
Storage usedcallee'scaller'scallee's (read-only)
msg.sender seenthe caller contractoriginal senderthe caller contract
Typical usenormal interactionproxy / upgradeablesafe view call

Where it is used

Interview questions

Common mistakes

Related topics

Blockchain security and smart-contract audits · Enterprise blockchains: Hyperledger Fabric and Corda · Solana: architecture, Rust programs and applications · Blockchain in finance and supply chain · Crypto-assets in India: tax, TDS and FIU registration · Consensus algorithms and cryptographic hashing

Open in the Knowledge reader →Find jobs →