Solidity Interview Questions and Answers

Answer : Solidity is a statically typed, contract-oriented, high-level programming language for writing smart contracts that run on the Ethereum Virtual Machine (EVM). Its syntax was influenced by C++, Python and JavaScript.

Answer : Contracts with state variables and functions, inheritance (including multiple inheritance), libraries, interfaces, user-defined types (structs and enums), modifiers, events, custom errors and built-in overflow checks (since version 0.8).

Answer : Smart contracts and the back ends of decentralized applications on Ethereum and other EVM-compatible chains – for example tokens (ERC-20), NFTs (ERC-721/1155), voting and DAO systems, crowdfunding, decentralized exchanges and lending platforms.

Answer : Solidity is designed specifically for the EVM. Code runs on every node of a blockchain, every operation costs gas, deployed code is immutable, state is stored permanently on-chain, and there is no direct access to files, network or system time. General-purpose languages run on a single machine without these constraints.

Answer : The Solidity compiler (solc) translates human-readable Solidity code into EVM bytecode – a sequence of low-level opcodes. This bytecode is what is stored on the blockchain and executed by the EVM on every node.

Answer : An enum is a user-defined type with a fixed set of named values, e.g. enum Status { Pending, Active, Closed }. It must have at least one member, it can be explicitly converted to and from integer types (the conversion is range-checked at run time and reverts if out of range), but there is no implicit conversion.

Answer : The EVM is the sandboxed, deterministic runtime environment present in every Ethereum node that executes contract bytecode. It is a 256-bit stack machine; it isolates contract code from the host computer so that every node reaches the same result.

Answer : A library is reusable code deployed once and used by contracts. Libraries with only internal functions are embedded (inlined) into the calling contract at compile time; libraries with public/external functions are deployed separately with their own address and linked, and their code runs in the caller’s context via DELEGATECALL.

Answer : It lets the nodes of a blockchain agree on which transactions are valid and in what order blocks are added, so all honest nodes keep the same ledger and unauthorised changes are rejected – without relying on a central authority.

Answer : Ethereum is an open-source, decentralized, programmable blockchain secured by Proof-of-Stake. Its native currency is Ether (ETH) and it runs smart contracts on the EVM, enabling decentralized applications that are not controlled by any single entity.

Answer : Blockchain is the underlying technology – a replicated, hash-linked ledger. Bitcoin is a specific blockchain and cryptocurrency focused on peer-to-peer money, using Proof-of-Work and limited scripting. Ethereum is a different blockchain designed as a programmable platform for smart contracts, using Proof-of-Stake and the native currency ETH.

Answer : Automatic, trust-minimised execution; transparent and verifiable code; tamper-resistant state; composability with other contracts; and global, 24×7 availability without intermediaries. These benefits come with responsibilities such as careful security review, because deployed code is hard to change.

Answer : Development and testing frameworks such as Hardhat and Foundry, the browser-based Remix IDE, linters such as Solhint, static analysers such as Slither, and testnets such as Sepolia. (Truffle and Ganache, used in older tutorials, have been sunset by their maintainer.)

Answer : Yes – for, while and do-while loops are supported, including iterating over arrays. However, loops over data that can grow without limit are dangerous: every iteration costs gas, and a loop that exceeds the block gas limit will always fail, which can permanently block a function.

Answer : A view function reads but does not modify contract state; a pure function neither reads nor modifies state. Since Solidity 0.5.0 the old constant keyword for functions is no longer allowed and view/pure are used instead. When called off-chain they cost no gas.

Answer : State variables declared at contract level are stored in the contract’s persistent storage on the blockchain. They keep their values between transactions and can be changed by the contract’s functions (unless declared constant or immutable). Writing to storage is the most expensive operation in terms of gas.

Answer : Normally an SPDX licence identifier comment (e.g. // SPDX-License-Identifier: MIT) followed by the version pragma (e.g. pragma solidity ^0.8.20;). The pragma tells the compiler which versions may compile the file, avoiding incompatibilities between compiler versions.

Answer : The Application Binary Interface is a JSON description of a contract’s public interface – function names, parameter and return types, events and errors. It tells off-chain code and other contracts how to encode calls and decode results, but does not contain the implementation.

Answer : Solidity is a statically typed, contract-oriented (object-oriented-style) high-level language with curly-brace syntax that will look familiar to developers who know JavaScript, C++ or Java.

Answer : eth_call executes a read-only call locally on a node – it changes no state, needs no signature, costs nothing and returns a value. eth_sendRawTransaction (or eth_sendTransaction for node-managed accounts) submits a signed transaction that can change state, costs gas, is recorded on-chain and returns a transaction hash rather than the function’s return value.

References: Solidity Team. (n.d.). Solidity Documentation (latest). · Solidity Team. (n.d.). Contracts (creating contracts, visibility and getters, function modifiers, constant and immutable, functions, events, custom errors, inheritance, abstract contracts, interfaces, libraries). Solidity Documentation. · Solidity Team. (n.d.). Security Considerations. Solidity Documentation. · ethereum.org. (n.d.). Introduction to smart contracts. Ethereum Developer Documentation. · Antonopoulos, A. M., & Wood, G. (2018). Mastering Ethereum: Building Smart Contracts and DApps. O’Reilly Media.

Prerequisite : Prerequisite : Programming Basics for Solidity

Read the notes, watch the video & take the MCQ test »

Answer : A variable is a named storage location that holds a value which can be read and changed by a program. In Solidity every variable has a fixed data type, for example uint count = 10;.

Answer : A data type defines what kind of value a variable can store (integer, boolean, text, address …) and which operations are allowed on it. It lets the compiler reserve the right amount of space and catch mistakes such as adding a number to text.

Answer : A compiled language is translated by a compiler into lower-level code before it runs; an interpreted language is executed line by line by an interpreter at run time. Solidity is compiled by solc into EVM bytecode.

Answer : In a statically typed language the type of every variable is known and checked at compile time. Solidity is statically typed, so type errors are reported by the compiler before the contract is deployed.

Answer : A function is a reusable block of code that performs a task. Its main parts are the name, the parameters (inputs), the body (statements) and the return values (outputs).

Answer : A parameter is an input passed into a function when it is called; a return value is the output the function sends back to the caller after it finishes.

Answer : Conditional statements such as if/else let a program choose which block of code to run depending on whether a condition is true or false.

Answer : Loops repeat a block of code while a condition remains true, avoiding duplicated code – for example adding up all the values in an array.

Answer : An array is an ordered collection of elements of the same data type, where each element is accessed by its index starting from 0.

Answer : A class is a blueprint that defines data (fields) and behaviour (methods); an object is a concrete instance created from that blueprint. In Solidity a contract plays the role of a class and a deployed contract instance plays the role of an object.

Answer : Inheritance lets a new (child) class reuse and extend the data and functions of an existing (parent) class. Solidity supports it with the is keyword, including multiple inheritance.

Answer : A smart contract is a program stored on a blockchain at a specific address. It contains data (state) and functions, and it executes exactly as written on every node of the network.

Answer : Gas is the unit that measures computational work on Ethereum. Every state-changing operation costs gas paid in Ether, so efficient code is cheaper for users and long loops can make a function too expensive to run.

Answer : Deployed contract code is immutable – it cannot simply be edited. Contracts often hold valuable assets, and bugs can be exploited by anyone, so mistakes are costly and hard to fix.

Answer : Solidity’s syntax was influenced mainly by C++, Python and JavaScript, so its curly-brace blocks, semicolons and operators look familiar to developers who know these languages.
MCQ Answer Key
No.QuestionCorrect Answer
1Solidity source code is converted into EVM bytecode by:B. The solc compiler
2In Solidity, a contract is most similar to which OOP concept?C. Class
3A statically typed language checks variable types:A. At compile time
4Which statement about deployed smart-contract code is TRUE?D. It is immutable once deployed
51 ether is equal to:C. 10^18 wei
Ch-1 : Solidity / Remix : Solidity and Remix IDE Setup

Read the notes, watch the video & take the MCQ test »

Answer : Solidity is a statically typed, contract-oriented, high-level programming language for writing smart contracts that run on the Ethereum Virtual Machine (EVM) and other EVM-compatible blockchains.

Answer : Solidity’s design was influenced mainly by C++, Python and JavaScript.

Answer : Solidity was proposed by Gavin Wood in August 2014. It was then developed by the Ethereum project’s Solidity team, initially led by Christian Reitwiessner.

Answer : The EVM is the runtime environment present on every Ethereum node that executes contract bytecode deterministically, so all nodes reach the same result.

Answer : Bytecode, which is deployed and executed by the EVM, and the ABI (Application Binary Interface), a JSON description of the contract’s functions and events used by front ends and other tools to call the contract.

Answer : Remix is a browser-based IDE for writing, compiling, deploying, testing and debugging smart contracts. It needs no installation, provides a built-in test blockchain (Remix VM) and shows results immediately, which makes it ideal for beginners.

Answer : File Explorer, Solidity Compiler, Deploy & Run Transactions, Terminal and Debugger (plus optional plugins).

Answer : Remix VM is an in-browser simulated blockchain with pre-funded test accounts. Transactions are instant and free of real cost, so it is used for learning and quick testing.

Answer : It connects Remix to a browser wallet such as MetaMask so contracts can be deployed to and used on a real network such as a testnet or mainnet, with the wallet signing the transactions.

Answer : setMessage changes contract storage, so it must be sent as a transaction that every node executes and records. Reading a public variable only queries a node locally (a call) and does not change state.

Answer : A deployment transaction containing the creation bytecode is executed; the constructor runs, the runtime bytecode is stored on the blockchain and the contract receives its own address.

Answer : No. Solidity targets the EVM, so it is also used on other EVM-compatible blockchains and Layer-2 networks.

Answer : Voting systems, crowdfunding platforms, auctions, tokens (ERC-20/721), multi-signature wallets and lotteries are common examples.

Answer : Different compiler versions support different language features and may behave differently. The version must satisfy the file’s pragma, otherwise compilation fails.

Answer : The 0.8.x series; the examples were compiled with solc 0.8.26. Version 0.8 added important safety features such as automatic overflow checks.
MCQ Answer Key
No.QuestionCorrect Answer
1Solidity is designed to target:B. The Ethereum Virtual Machine
2Which file describes a contract’s functions so a front end can call it?A. ABI
3Which Remix environment is an in-browser test blockchain with pre-funded accounts?C. Remix VM
4Solidity was proposed in 2014 by:D. Gavin Wood
5Calling a function that changes a state variable requires:B. A transaction that costs gas
Ch-2 : Basic Syntax : Solidity Basic Syntax

Read the notes, watch the video & take the MCQ test »

Answer : A pragma is a compiler directive. The version pragma, e.g. pragma solidity ^0.8.20;, states which compiler versions are allowed to compile the file.

Answer : The file can be compiled with version 0.8.20 or any later 0.8.x version, but not with 0.9.0 or higher.

Answer : It allows any compiler version from 0.8.2 up to, but not including, 0.9.0.

Answer : No. A version pragma applies only to the source file in which it is written; every imported file has its own pragma.

Answer : SPDX (Software Package Data Exchange) is an open standard (ISO/IEC 5962:2021) for communicating licence information. Solidity files start with a comment such as // SPDX-License-Identifier: MIT to declare their licence in a machine-readable way.

Answer : The compiler issues a warning (not an error). The contract still compiles, but adding the identifier is recommended, especially for published source code.

Answer : UNLICENSED, i.e. // SPDX-License-Identifier: UNLICENSED.

Answer : A contract is a collection of code (functions) and data (state) that resides at a specific address on the blockchain. It is similar to a class in object-oriented programming.

Answer : No. Ethereum has no built-in cron or scheduler; a contract function runs only when a transaction or another contract calls it. Off-chain automation services must send that call.

Answer : import "./Token.sol"; imports all symbols, and import {Token} from "./Token.sol"; imports only the named symbol.

Answer : NatSpec comments use /// or /** */ with tags such as @title, @author, @notice, @dev, @param and @return to document contracts and functions for users, developers and tools.

Answer : @notice explains to end users what a function does; @dev gives extra technical details for developers.

Answer : Contract names use CapWords (e.g. VotePanel); function and variable names use mixedCase (e.g. totalSupply).

Answer : In upper case with underscores, for example MAX_SUPPLY.

Answer : The call switches execution context to the other contract, so the caller’s state variables are not directly accessible inside the called contract; data must be passed as arguments.
MCQ Answer Key
No.QuestionCorrect Answer
1Which line is normally the first line of a Solidity file?A. // SPDX-License-Identifier: MIT
2Which compiler version is NOT allowed by pragma solidity ^0.8.20;?D. 0.9.0
3SPDX identifiers describe a file’s:B. Software licence
4Which comment style is used for NatSpec documentation?C. /// comment
5According to the Solidity style guide, a constant should be named:D. MAX_SUPPLY
Ch-3 : DataTypes : Solidity Data Types

Read the notes, watch the video & take the MCQ test »

Answer : A value-type variable stores the data itself and is copied when assigned or passed to a function (e.g. uint, bool, address). A reference-type variable refers to the location of the data, so it may be shared, and it needs a data location (storage, memory or calldata) inside functions (e.g. arrays, string, struct, mapping).

Answer : The address type stores a 20-byte Ethereum address of a user account or a contract. It is used to identify owners, senders and recipients and provides members such as .balance.

Answer : Both store a 20-byte address, but only address payable has the .transfer() and .send() members for sending Ether to it. A plain address is converted with payable(addr).

Answer : uint8 ranges from 0 to 255; int8 ranges from −128 to 127.

Answer : They are the same type: uint is an alias for uint256, and int is an alias for int256.

Answer : Use type(T).max, for example type(uint8).max returns 255; type(T).min returns the minimum.

Answer : No. fixed and ufixed can be declared but values cannot be assigned to or from them, so decimals are represented with integers, such as amounts in wei.

Answer : bool: false; uint: 0; address: the zero address 0x000…000; string: the empty string "". Solidity has no undefined or null values.

Answer : bytes32 is a fixed-size 32-byte value type, commonly used to store hashes such as the output of keccak256, or short identifiers.

Answer : bytes32 is a fixed-size value type holding exactly 32 bytes. bytes is a dynamically sized reference type that can hold any number of bytes.

Answer : A mapping is a key-value store similar to a hash table or dictionary: mapping(KeyType => ValueType) name;, for example mapping(address => uint) balances;.

Answer : A struct is a user-defined type that groups variables of different types into one record, for example a Student with name, roll number and marks.

Answer : Integer/rational literals (42, 1e18), string literals ("abc"), hexadecimal literals (hex"00ff"), Unicode literals (unicode"₹") and checksummed address literals.

Answer : A struct cannot directly include itself as a field because that would require infinite size. It can, however, contain a dynamic array of its own type or be the value type of a mapping member.

Answer : Its range is small (0–255). Since Solidity 0.8, exceeding it makes the transaction revert with an overflow error, so the type must fit every value the variable may hold.
MCQ Answer Key
No.QuestionCorrect Answer
1Which of the following is a REFERENCE type?C. string
2An Ethereum address occupies:A. 20 bytes
3What is the default value of a bool variable?D. false
4What is the maximum value of uint8?B. 255
5Which member is available on address payable but not on plain address?C. .transfer()
Ch-4 : Variable : Solidity Variables and Data Locations

Read the notes, watch the video & take the MCQ test »

Answer : State variables (declared at contract level and stored permanently in storage), local variables (declared inside functions and existing only during the call) and global variables (pre-defined values such as msg.sender and block.timestamp).

Answer : State variables are stored in the contract’s storage on the blockchain. Every node must keep that data permanently, so writing to storage costs much more gas than working with temporary data.

Answer : At declaration (e.g. uint x = 5;), inside the constructor at deployment, or later through a setter function called by a transaction.

Answer : A constant’s value is fixed in the source code at compile time. An immutable variable is assigned once at deployment, normally in the constructor. Neither can change afterwards, and neither occupies a storage slot, so both are cheap to read.

Answer : storage (permanent, on-chain), memory (temporary, exists during the function call and can be modified) and calldata (temporary and read-only, holds function input data).

Answer : calldata is read directly from the transaction input without copying it into memory, and it cannot be modified, which avoids extra copy operations.

Answer : No. Value types such as uint, bool and address live on the EVM stack; only reference types (string, bytes, arrays, structs) need storage, memory or calldata.

Answer : No. State variables are always stored in storage; memory and calldata can only be used for local variables, parameters and return values.

Answer : An independent copy is created in memory. Changing the memory copy does not change the state variable.

Answer : The local variable becomes a reference (pointer) to the state variable, so changes made through it update the stored state.

Answer : string is a reference type of dynamic size, so the compiler must know where the data lives during the function call; memory or calldata (for parameters) must be stated explicitly.

Answer : msg.sender (address of the current caller) and block.timestamp (timestamp of the current block). Others include msg.value and block.number.

Answer : Memory exists only for the duration of an external function call; once execution finishes it is cleared, similar to RAM.

Answer : Its value (60) never changes, so declaring it constant avoids a storage slot and makes every read cheaper.

Answer : When the value is only known at deployment (for example the admin address taken from msg.sender) and never changes afterwards; immutable saves gas on every read.
MCQ Answer Key
No.QuestionCorrect Answer
1Which data location is READ-ONLY?C. calldata
2A variable declared at contract level outside any function is a:A. State variable
3Which keyword declares a value assigned once in the constructor and never changed?D. immutable
4Assigning a storage array to a memory variable:B. Creates an independent copy
5Which of these is a global variable?C. msg.sender
Ch-5 : Scope of Variables : Scope and Visibility of Variables

Read the notes, watch the video & take the MCQ test »

Answer : Scope is the region of the program in which a variable can be used. Local variables are limited to their block; state variables are available throughout the contract, and their visibility controls access from other contracts.

Answer : From the point where it is declared to the end of the enclosing { } block, following C99 scoping rules. It cannot be used outside that block.

Answer : public, internal and private.

Answer : internal.

Answer : Internal variables can be accessed inside the current contract and in contracts derived from it. Private variables can be accessed only inside the contract where they are defined, not in derived contracts.

Answer : For every public state variable the compiler generates an external view function with the same name that returns its value, e.g. publicData(). For arrays and mappings the getter takes an index or key as a parameter.

Answer : No. external is a visibility for functions only. State variables can be public, internal or private.

Answer : No. private only prevents other contracts from accessing the variable through code. All blockchain storage is public, so anyone can read the value using a node or block explorer.

Answer : Contract storage and transaction inputs are visible to everyone on the blockchain, so any stored password could be read and misused.

Answer : By calling its getter function through a contract reference, for example p.publicData().

Answer : square is declared inside the loop body block, so its scope ends at that block’s closing brace; it does not exist after the loop.

Answer : Yes. Internal members are accessible in the contract that defines them and in all contracts that inherit from it.

Answer : Directly by its name, like any internal variable (e.g. publicData). Calling the getter with this.publicData() would make an external call, which is unnecessary and costs more gas.

Answer : function balances(address) external view returns (uint), which takes a key and returns the stored value.

Answer : It defines which contracts can access or rely on a variable. Overly broad visibility can expose internal logic to misuse, while correct visibility keeps the contract’s design clear and reduces mistakes.
MCQ Answer Key
No.QuestionCorrect Answer
1Which visibility automatically creates a getter function?C. public
2The default visibility of a state variable is:A. internal
3A private variable of a parent contract is accessible in:D. Only the contract that defines it
4A local variable declared inside a for-loop body can be used:B. Only inside that loop body block
5Which statement about private state variables is TRUE?C. Their values can still be read by anyone off-chain
Ch-6 : Operators : Solidity Operators

Read the notes, watch the video & take the MCQ test »

Answer : Arithmetic, assignment (including compound assignment), relational (comparison), logical, bitwise and shift, and the ternary (conditional) operator.

Answer : 3. Solidity has no floating-point numbers, so integer division truncates the result towards zero.

Answer : It returns the remainder of integer division, e.g. 7 % 2 = 1.

Answer : The operation reverts the transaction with a Panic error, instead of silently wrapping around as it did in versions before 0.8.

Answer : unchecked { ... } disables overflow/underflow checks inside the block, so results wrap around and gas is saved. It should be used only when overflow is impossible, for example a loop counter with a known small bound.

Answer : The transaction reverts with a Panic error; division and modulus by zero are always checked.

Answer : = is the assignment operator that stores a value in a variable; == is the relational operator that compares two values and returns a bool.

Answer : In a && b, b is not evaluated when a is false; in a || b, b is not evaluated when a is true. Ordering conditions well can save gas and avoid unnecessary calls.

Answer : condition ? valueIfTrue : valueIfFalse, e.g. uint larger = (a > b) ? a : b;.

Answer : 12 = 1100 and 10 = 1010 in binary. AND = 1000 = 8, OR = 1110 = 14, XOR = 0110 = 6.

Answer : x << n moves bits left n places, multiplying by 2^n (12 << 1 = 24); x >> n moves bits right, dividing by 2^n (12 >> 2 = 3).

Answer : -7 / 2 = -3 (truncated towards zero) and -7 % 2 = -1 (the remainder takes the sign of the left operand).

Answer : It resets a variable to its default value, e.g. delete on a uint sets it to 0, on a bool to false and on an array element to the element’s default.

Answer : No. Strings are dynamic reference types and == is not defined for them. Compare their hashes, e.g. keccak256(bytes(a)) == keccak256(bytes(b)).

Answer : total += price;
MCQ Answer Key
No.QuestionCorrect Answer
1For uint values, 9 / 4 evaluates to:B. 2
2In Solidity 0.8, uint8 x = 255; x = x + 1; (outside unchecked) will:C. Revert the transaction
3Which operator returns true only if both conditions are true?A. &&
4What is 12 >> 2?D. 3
5Which statement about unchecked { } is correct?A. It disables overflow checks so values wrap around
Ch-7 : Decision Making : Decision Making (if, else if, else)

Read the notes, watch the video & take the MCQ test »

Answer : They are conditional statements that evaluate a boolean expression and decide which block of code to execute, controlling the flow of a program.

Answer : if (condition) { /* code to run if condition is true */ }

Answer : if (condition) { /* true block */ } else { /* false block */ }

Answer : if (c1) { ... } else if (c2) { ... } else if (c3) { ... } else { ... } – the first true condition’s block runs and the others are skipped.

Answer : Yes. Solidity does not convert numbers to booleans automatically, so if (count) is a compile error; write if (count != 0).

Answer : No. Multiple cases are handled with an if…else if…else chain.

Answer : Only the block of the first true condition runs; the remaining conditions are not even evaluated.

Answer : Because the first true branch wins. If marks >= 40 were tested before marks >= 90, a score of 95 would wrongly receive the lower grade.

Answer : For a simple choice between two values in a single expression, e.g. return marks >= 40 ? "Pass" : "Fail";. Complex logic is clearer with if…else.

Answer : No, they can be omitted for one statement, but always using braces makes code clearer and prevents mistakes when more statements are added later.

Answer : It validates the input before the decision logic runs; if marks exceed 100 the call reverts with the message “Marks must be 0-100”.

Answer : Use the modulus operator: if (n % 2 == 0) { /* even */ }.

Answer : It handles every case not matched by the previous conditions, acting as a default branch.

Answer : Yes, an if or else block can contain another if statement, although deep nesting reduces readability and is often replaced with else-if chains or early returns.

Answer : The AND operator: if (marks >= 40 && marks < 60) { ... }.
MCQ Answer Key
No.QuestionCorrect Answer
1Which of these conditions is VALID in Solidity?B. if (count != 0)
2Solidity’s replacement for a switch statement is:C. an if…else if…else chain
3With the GradeCalculator, grade(80) returns:A. A
4In an if…else if chain, how many blocks run at most?D. One
5marks >= 40 ? "Pass" : "Fail" with marks = 35 returns:A. "Fail"
Ch-8 : Loop : Loops in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : A loop repeatedly executes a block of statements while a condition remains true; when the condition becomes false, the loop ends.

Answer : while, do…while and for.

Answer : (a) A while loop can make 0 iterations because the condition is checked first. (b) A do…while loop makes at least 1 iteration because the condition is checked after the body.

Answer : for (initialisation; condition; update) { ... } – the initial value of the counter, the test condition and the increment/decrement step.

Answer : When the number of repetitions is known in advance, such as iterating over an array with an index; a while loop suits cases where repetitions depend on a changing condition.

Answer : It immediately exits the nearest enclosing loop and continues with the statement after the loop.

Answer : It skips the rest of the current iteration and jumps to the next iteration (re-checking the condition, and running the update step in a for loop).

Answer : Each iteration costs gas and every block has a gas limit. If a loop grows with data that users can add, it may eventually need more gas than allowed, making the function permanently unusable (a denial-of-service risk).

Answer : Use mappings for direct look-ups, cap the size of arrays, process data in fixed-size batches, or let users withdraw individually instead of looping over everyone.

Answer : When a view function is called off-chain (eth_call) the caller pays no fee, but execution is still limited by the node’s gas cap. If the view function is called inside a transaction, its gas is charged.

Answer : 1 + 2 + 3 + 4 = 10.

Answer : 4. The while loop divides n by 10 until it becomes 0, counting each division (2026 → 202 → 20 → 2 → 0).

Answer : Once. The body runs first, then the condition 6 < 3 is false, so the loop stops.

Answer : An infinite loop never meets its stop condition. In Solidity it runs until the transaction runs out of gas, at which point the transaction reverts and the gas used is lost.

Answer : To skip values that are not greater than the limit and move straight to the next element, keeping the loop body simple.
MCQ Answer Key
No.QuestionCorrect Answer
1Which loop always executes its body at least once?C. do…while
2Which statement exits a loop immediately?B. break
3The main risk of looping over a user-growable array in a transaction is:D. Exceeding the gas limit
4What does sumTo(5) return?C. 15
5In a for loop, which part runs after each iteration?B. Update (increment/decrement)
Ch-9 : String : Strings in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : A reference type. It is dynamically sized, so the variable refers to the location of the data and needs a data location (memory, calldata or storage) inside functions.

Answer : UTF-8. Internally a string is a byte array of its UTF-8 encoding.

Answer : Convert it to bytes and read the length: bytes(s).length. This returns the number of bytes, which can be larger than the number of characters for non-ASCII text.

Answer : The rupee sign is encoded in UTF-8 using three bytes, and the length counts bytes, not characters.

Answer : By comparing their hashes: keccak256(bytes(a)) == keccak256(bytes(b)). The == operator is not defined for strings.

Answer : With string.concat(a, b, ...), available from Solidity 0.8.12. Older code used string(abi.encodePacked(a, b)).

Answer : bytes memory bstr = new bytes(10); string memory message = string(bstr);

Answer : A returned string is a dynamic reference type that must be placed in a temporary location for the caller; memory is used for return values.

Answer : For parameters of external (or public) functions that only read the input. calldata is read-only and avoids copying the data into memory, which saves gas.

Answer : memory is temporary and exists only during the function call; storage is permanent and keeps the data on the blockchain between calls.

Answer : No. Index access is not allowed on string. Convert first: bytes(s)[0] returns the first byte as bytes1.

Answer : Use a Unicode literal, e.g. unicode"नमस्ते ₹". Regular string literals may contain only printable ASCII characters (plus escape sequences).

Answer : \" (double quote), ' (single quote), \n (new line), \ (backslash), \t (tab), \r (carriage return), \xNN (hex) and \uNNNN (Unicode).

Answer : bytes(s).length == 0.

Answer : Every byte stored in contract storage costs gas and is kept by every node, so long text increases deployment and transaction costs. Large data is usually stored off-chain with only a hash on-chain.
MCQ Answer Key
No.QuestionCorrect Answer
1Which expression correctly compares two strings a and b?C. keccak256(bytes(a)) == keccak256(bytes(b))
2bytes("Hello").length returns:C. 5
3Which function joins strings in Solidity 0.8.12 and later?B. string.concat
4Which data location is read-only and suited to external string parameters?D. calldata
5Solidity strings are encoded as:A. UTF-8
Ch-10 : Array : Arrays in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : An array is a collection of elements of the same data type stored in order, where each element is accessed by an index starting from 0.

Answer : Fixed-size arrays: <type>[size] name; e.g. uint[5] marks;. Dynamic arrays: <type>[] name; e.g. uint[] scores;.

Answer : arr.length - 1, because indexing starts at 0.

Answer : push(v) appends an element to the end and increases the length by one. It can be used only on dynamic arrays stored in storage (and on storage bytes).

Answer : pop() removes the last element and reduces the length by one. Calling it on an empty array reverts the transaction.

Answer : It resets the element at index i to its default value (e.g. 0) but does not shrink the array or change its length.

Answer : Copy the last element into the index to be removed and then call pop(). This is gas-efficient but changes the order of elements.

Answer : With the new keyword: uint[] memory a = new uint[](n);. Its length is fixed once created, so push and pop are not available.

Answer : A slice x[start:end] is a view of part of an array, from start up to (not including) end. Slices are currently supported only for calldata arrays.

Answer : The access reverts with a Panic error (array out of bounds); Solidity checks array indexes automatically.

Answer : It takes an index and returns a single element, e.g. scores(0). To return the whole array, write a function returning uint[] memory.

Answer : Its length is always 5; the size of a fixed-size array cannot change.

Answer : Copying a large storage array into memory consumes a lot of gas; if it exceeds the gas cap the call fails, so large datasets should be paged or read off-chain.

Answer : uint total; for (uint i = 0; i < scores.length; i++) { total += scores[i]; }

Answer : By adding more brackets, e.g. uint[][] grid; or uint[3][2] table;. Note that uint[3][2] is two arrays of three elements each (the notation is reversed compared with some other languages).
MCQ Answer Key
No.QuestionCorrect Answer
1Which declaration creates a FIXED-size array of 5 unsigned integers?C. uint[5] a;
2After delete arr[1] on a 4-element uint array, the length is:A. 4
3Which operation is NOT available on a memory array created with new?D. arr.push(x)
4Array slices like data[0:2] are supported for:A. calldata arrays
5Accessing arr[arr.length] will:B. Revert with a Panic error
Ch-11 : Enum : Enums in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : An enum is a user-defined type whose variables can only take one of a fixed set of named constant values, for example enum Status { Placed, Shipped, Delivered }.

Answer : Members follow their natural order – the order in which they are declared. The first member has the value 0, the second 1, and so on.

Answer : Its first member, whose integer value is 0.

Answer : At least one member and at most 256 members.

Answer : As the smallest unsigned integer type that can hold all its values – uint8 for enums with up to 256 members.

Answer : Explicitly: uint(status) converts to an integer, and Status(n) converts an integer back. Implicit conversion is not allowed.

Answer : The conversion is checked at run time and the transaction reverts with a Panic error.

Answer : With type(Status).min and type(Status).max.

Answer : Yes, enums can be declared at file level so that multiple contracts in the file (or files that import it) can use them.

Answer : In the ABI an enum is represented as a uint8 number, so the front end receives and sends numeric values.

Answer : More readable code, fewer errors because only valid members are allowed, and clear modelling of contract states; they are also cheap to store.

Answer : A state machine is a design in which a contract moves through defined stages and allows certain actions only in certain stages. An enum stores the current stage, and require checks enforce valid transitions.

Answer : The initial status is Placed, but deliver() requires the status to be Shipped, so the require check fails and the call reverts.

Answer : No. An enum declaration ends with the closing brace and no semicolon.

Answer : enum candidateCode {AJIT, ASHISH, MAYANK, KUNAL, NOTA}. It gives each candidate a readable name that is converted to a number to use as the key of the candidate mapping.
MCQ Answer Key
No.QuestionCorrect Answer
1For enum Color { Red, Green, Blue }, what is uint(Color.Blue)?D. 2
2The default value of an enum variable is:A. Its first member
3The maximum number of members in an enum is:C. 256
4Converting Status(10) when Status has 4 members will:B. Revert
5In the ABI, an enum value is passed as:D. uint8
Ch-12 : Mapping : Mapping in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : Like a hash table or dictionary, a mapping stores key-value pairs and gives direct access to a value by its key. The location of each value is computed from a hash (keccak256) of the key.

Answer : mapping(KeyType => ValueType) visibility name;, for example mapping(address => uint) public balances;.

Answer : Any built-in value type (uint, address, bool, bytes32 …), bytes, string, contract types and enums. Mappings, structs and arrays cannot be used as keys.

Answer : Any type, including structs, arrays and other mappings.

Answer : The default value of the value type – for example 0 for uint, false for bool or the zero address for address.

Answer : The keys are not stored; only values are stored at locations derived from key hashes. Since the contract does not know which keys were used, it cannot count or iterate them.

Answer : Maintain a separate array that stores every key when it is first added, then loop over the array and read each key’s value from the mapping.

Answer : Only storage. Mappings are used as state variables or storage references and cannot be created in memory.

Answer : An external view function balances(address) that takes a key and returns the corresponding value.

Answer : A mapping whose value type is another mapping, e.g. mapping(address => mapping(address => uint)) allowance;, used in ERC-20 tokens to store how much each owner allows each spender to use.

Answer : Both read as 0, so store extra information such as a separate mapping(key => bool) isRegistered or a struct with an exists flag.

Answer : It resets the value for that key to its default (0). The key itself is not “removed” because keys are never stored.

Answer : Since Solidity 0.8.18 you can name the key and value for readability, e.g. mapping(address user => uint balance) balances;. The names do not change behaviour.

Answer : A mapping finds a value directly in constant time and cost, while searching an array requires a loop whose gas cost grows with the array size.

Answer : It records each registered roll number so that totalMarks() can loop over all keys, something the mapping alone cannot do.
MCQ Answer Key
No.QuestionCorrect Answer
1Which of these CANNOT be used as a mapping key?D. struct
2Reading balances[x] for an address never set returns:A. 0
3Mappings can be stored in:C. storage only
4Which statement is TRUE about mappings?B. They cannot be iterated directly
5mapping(address => mapping(address => uint)) is an example of a:A. Nested mapping
Ch-13 : Struct : Structs in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : A struct is a user-defined type that groups several variables, possibly of different types, into one record – for example a Student with name, roll number and marks.

Answer : struct StructName { type1 member1; type2 member2; }

Answer : Inside a contract (available to that contract and contracts that inherit from it), or outside a contract at file level, from where it can be imported and shared by multiple contracts.

Answer : Positional arguments: Student("Asha", 101, 92); named arguments: Student({name: "Ravi", roll: 102, marks: 85}); or declare an empty memory struct and assign each member separately.

Answer : A reference type, so when used in a function it must have a data location such as storage or memory.

Answer : A storage variable is a reference to the struct stored on the blockchain, so changes are saved. A memory variable is a temporary copy, so changes are lost after the function ends.

Answer : It loads the struct into memory, which creates a copy; modifying the copy does not affect storage, and the function is declared view, so it cannot change state anyway.

Answer : Declare Student[] students; and use students.push(s), or declare mapping(uint => Student) byRoll; and assign byRoll[roll] = s.

Answer : Not directly, because that would need infinite size. It can, however, contain a dynamic array of its own type or be the value type of a mapping member.

Answer : It resets every member of that struct to its default value (empty string, 0, false …); the array length does not change.

Answer : Yes. With ABI coder v2, which is the default in Solidity 0.8, public and external functions can return structs; they are encoded as tuples.

Answer : With the dot operator, e.g. s.marks or students[0].name.

Answer : For example Candidate in CandidateMaster.sol (Election System), UserRecord in UserRecord.sol (Lottery) and the ItemMaster, BiddersMaster and AuctionRegister structs in BlockMaster.sol (e-Auction).

Answer : It takes an index and returns the struct’s members as separate values (for members of supported types), e.g. students(0) returns name, roll and marks.

Answer : They keep related data together, make code easier to read and maintain, and let contracts model real-world records such as voters, bids, tickets or rides.
MCQ Answer Key
No.QuestionCorrect Answer
1A struct is used to:B. Group related variables of different types
2Which statement updates a stored struct permanently?B. Student storage s = students[0]; s.marks = 90;
3Student({name: "Ravi", roll: 2, marks: 80}) creates a struct using:C. Named arguments
4Structs declared outside a contract are shared with other files using:D. import
5A struct cannot directly contain:D. A member of its own type
Ch-14 : Global Variables : Global Variables and Special Functions

Read the notes, watch the video & take the MCQ test »

Answer : Pre-defined variables and functions that are always available, giving information about the current call (msg), block (block) and transaction (tx), plus utility functions such as keccak256 and gasleft().

Answer : The address of the account or contract that made the current call. It changes at each step of a call chain.

Answer : msg.sender is the immediate caller of the current function; tx.origin is the externally owned account that started the entire transaction. If Alice calls contract A, which calls contract B, then inside B msg.sender is A while tx.origin is Alice.

Answer : A malicious contract that the owner is tricked into calling can call your contract while tx.origin is still the owner, bypassing the check (a phishing-style attack). Use msg.sender instead.

Answer : msg.value is the amount of wei sent with the call. It can be non-zero only in payable functions; non-payable functions reject Ether.

Answer : The current block’s timestamp in seconds since the Unix epoch (1 January 1970).

Answer : now was an alias for block.timestamp and was removed in Solidity 0.7.0; code must use block.timestamp.

Answer : block.prevrandao, after Ethereum moved from Proof-of-Work to Proof-of-Stake (EIP-4399). Under PoS there is no mining difficulty, and the DIFFICULTY opcode now returns the beacon chain randomness value.

Answer : Only for the 256 most recent blocks, excluding the current block. For other block numbers it returns zero.

Answer : The first four bytes of the call data, i.e. the function selector that identifies which function is being called.

Answer : With address(this).balance, which returns the balance in wei.

Answer : Ether units: wei, gwei and ether (1 ether = 10^18 wei). Time units: seconds, minutes, hours, days and weeks.

Answer : They are known to everyone once the block is produced and can be partly influenced by block producers, so players or validators could predict or manipulate outcomes. Verifiable randomness (VRF) or commit-reveal schemes are safer.

Answer : It returns the amount of gas remaining in the current call. It can be used to measure gas usage or to stop long operations before running out of gas.

Answer : No. Since 0.8.0 msg.sender is a plain address; to send Ether to it you convert it with payable(msg.sender).
MCQ Answer Key
No.QuestionCorrect Answer
1Alice calls contract A, which calls contract B. Inside B, msg.sender is:C. Contract A
2Which global variable should be used for access control?A. msg.sender
3Which keyword was removed in Solidity 0.7.0?B. now
41 ether equals:D. 10^18 wei
5Which value replaced block.difficulty after the move to Proof-of-Stake?C. block.prevrandao
Ch-15 : Functions : Functions in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : A function is a named block of code that performs a task, optionally taking parameters and returning values. Functions define a contract’s behaviour and are called by users or other contracts.

Answer : function name(parameters) visibility [mutability] [modifiers] [returns (types)] { ... }, e.g. function add(uint a, uint b) public pure returns (uint) { return a + b; }.

Answer : public, external, internal and private.

Answer : Internal functions can be called inside the current contract and in contracts that inherit from it. Private functions can be called only inside the contract that defines them, not in derived contracts.

Answer : Public functions can be called both internally and externally. External functions can only be called from outside (or internally via this.f(), which is an external call); their parameters can be calldata, which can save gas.

Answer : A view function may read state but not modify it. A pure function neither reads nor modifies state and works only with its inputs and local variables. Both are free when called off-chain.

Answer : A function marked payable can receive Ether with the call; the amount is available in msg.value. A function without payable rejects any Ether sent to it.

Answer : Yes. function divide(uint a, uint b) public pure returns (uint q, uint r) { q = a / b; r = a % b; } returns both the quotient and remainder.

Answer : Return values given names in the returns clause. They act as local variables initialised to default values and are returned automatically when the function ends.

Answer : Defining several functions with the same name but different parameter types or counts, such as area(uint) and area(uint, uint). The compiler chooses the correct one from the arguments.

Answer : The compiler reports an error, because pure functions are not allowed to read or modify state.

Answer : It is a common naming convention (used by many libraries) that signals the function is not part of the public interface; it has no effect on behaviour.

Answer : Non-payable: it can read and modify state but rejects Ether. There is no keyword for it – it applies when view, pure or payable is not written.

Answer : Leave its position empty when destructuring, e.g. (uint q, ) = divide(17, 5);.

Answer : Not when called off-chain via eth_call. If a view function is called from inside a transaction (by another function), its execution gas is part of that transaction’s cost.
MCQ Answer Key
No.QuestionCorrect Answer
1A function that reads state but does not modify it should be marked:B. view
2Which visibility allows calls ONLY from the same contract (not children)?D. private
3Which function can receive Ether?A. function pay() external payable {}
4Two functions named area with different parameter lists is an example of:C. Overloading
5In the example, useDivide() returns:B. 3
Ch-16 : Contracts : Contracts in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : A contract is a collection of code (functions) and data (state) that resides at a specific address on the blockchain. It is the fundamental building block of Ethereum applications.

Answer : POP (e.g. C) organises code into functions that act on separate data; OOP (e.g. C++, Java, C#) uses classes that combine state and methods; BOP (the course’s term for Solidity) uses contracts that combine state and functions stored permanently on the blockchain.

Answer : Pragma is generally the first line of code (after the SPDX line) in a Solidity file. The version pragma specifies which compiler versions may compile the file.

Answer : SPDX is an open standard (ISO/IEC 5962:2021) for communicating software licence and supply-chain information. In Solidity, the comment // SPDX-License-Identifier: MIT declares the file’s licence.

Answer : State variables, functions, function modifiers, events, custom errors, struct and enum types, and a constructor.

Answer : With the new keyword, e.g. Wallet w = new Wallet(msg.sender, label);. This deploys a new instance and returns a reference to it.

Answer : Convert the contract variable: address(w). Inside a contract, address(this) gives its own address.

Answer : A contract marked abstract, typically because at least one function has no implementation. It cannot be deployed and serves as a base contract for inheritance.

Answer : A library is a reusable unit of code without its own state, used to share functions (such as maths helpers) among contracts.

Answer : Through a variable of that contract’s type pointing to its address, e.g. wallets[index].owner(); this performs an external message call.

Answer : Yes. Variables, arrays and parameters can have contract types (e.g. Wallet[] wallets), and they can be converted to and from addresses.

Answer : Like a class it defines state and behaviour together, supports inheritance and has a constructor; a deployed contract instance is similar to an object, except that it lives permanently on the blockchain.

Answer : The runtime bytecode is stored at the contract’s address and cannot be changed. State can change only through the contract’s own functions.

Answer : The account that called createWallet, because msg.sender is passed to the Wallet constructor.

Answer : No. A contract executes only when a transaction or another contract calls one of its functions.
MCQ Answer Key
No.QuestionCorrect Answer
1A contract in Solidity is a combination of:A. Functions and state at an address
2Which keyword deploys a contract from another contract?C. new
3An abstract contract:B. Cannot be deployed directly
4Which unit has NO state of its own and provides reusable functions?D. Library
5In this course, BOP stands for:A. Block Oriented Programming
Ch-17 : Constructor : Constructors in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : A constructor is a special function declared with the constructor keyword that initialises a contract’s state. It runs exactly once, when the contract is deployed.

Answer : No. It runs only during deployment, and its code is not part of the deployed runtime bytecode, so it can never be called again.

Answer : The compiler provides a default constructor that does nothing, equivalent to constructor() {}.

Answer : Only one. Solidity does not support constructor overloading.

Answer : Constructors set up the contract’s initial state at deployment – for example the owner address, limits or initial data – using values provided at deployment time. This guarantees that the contract starts in a valid state.

Answer : Whenever values must be set at creation: the contract owner (msg.sender), a maximum token supply, a ticket price, an initial candidate list, or configuration flags.

Answer : No. Since Solidity 0.7.0 constructor visibility is no longer used. To prevent a contract from being deployed on its own, it is marked abstract instead.

Answer : A constructor marked payable can receive Ether in the deployment transaction, so the contract starts with a balance.

Answer : An immutable value can be set only once during construction; after deployment it is fixed and stored in the contract code, making reads cheap.

Answer : In the inheritance list, e.g. contract B is A(10) {}, or in the derived constructor’s header, e.g. constructor(uint x) A(x) { }.

Answer : The derived contract must be declared abstract; it cannot be deployed until a further derived contract provides the arguments.

Answer : Remix shows input fields next to the Deploy button; the values entered there are encoded into the deployment transaction.

Answer : No. Only the runtime code that results from running the constructor is stored at the contract’s address.

Answer : msg.sender – the account that deployed the contract – because the Course constructor passes msg.sender to the Owned base constructor.

Answer : Because the constructor runs only once; if invalid values are stored at deployment, the contract may be permanently misconfigured. A require check rejects the deployment instead.
MCQ Answer Key
No.QuestionCorrect Answer
1A constructor runs:B. Once, at deployment
2How many constructors can a Solidity contract have?A. One
3Which keyword lets a constructor receive Ether during deployment?D. payable
4Since Solidity 0.7.0, to prevent direct deployment of a base contract you:C. Mark the contract abstract
5contract B is A(10) {} passes 10 to:A. A’s constructor
Ch-18 : Inheritance : Inheritance in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : Inheritance allows a derived contract to reuse the state variables and functions of one or more base contracts and to extend or override them. It is declared with the is keyword.

Answer : In single (single-level) inheritance, the functions and variables of one base contract are inherited by only one derived contract, e.g. contract B is A.

Answer : In multiple inheritance a single contract inherits from more than one parent contract, e.g. contract C is A, B. Solidity supports this, unlike Java.

Answer : A chain of inheritance in which a child contract is itself the parent of another contract, e.g. Person → Student → Monitor.

Answer : One parent contract has several child contracts, e.g. Vehicle → Car and Vehicle → Bike. It is used when common functionality is shared by different contracts.

Answer : All non-private members: public and internal state variables and functions. Private members cannot be accessed by the child.

Answer : virtual marks a function that derived contracts are allowed to override. override marks the function in the derived contract that replaces it. Both are required for overriding.

Answer : The function name, parameter types and return types. If they differ, it is treated as a different function or causes a compilation error.

Answer : With super.functionName(), which calls the next contract in the linearization, or explicitly with ParentName.functionName().

Answer : C3 linearization is the algorithm Solidity uses to determine a single order of base contracts for multiple inheritance. Parents must be listed from most base-like to most derived; an order that cannot be linearized causes a compile error.

Answer : Because A is more base-like than B but is listed after it. Solidity reports “Linearization of inheritance graph impossible”. The valid order is contract C is A, B.

Answer : One. The code of all parents is compiled into the single derived contract.

Answer : The version in the next contract of the linearized order, giving preference to the most derived contracts rather than simply the parent named first.

Answer : Either in the inheritance list, e.g. contract B is A(5), or in its own constructor header, e.g. constructor(string memory n) Person(n) {}.

Answer : “Asha is a Class Monitor (elected)”. Monitor’s describe() calls super.describe(), which runs Person.describe(); that calls role(), which resolves to the most derived override in Monitor.
MCQ Answer Key
No.QuestionCorrect Answer
1Which keyword declares that contract B inherits from contract A?C. is
2To allow a function to be overridden, the parent function must be marked:B. virtual
3A parent contract with several child contracts is:D. Hierarchical inheritance
4Which members of a parent are NOT accessible in a child contract?B. private
5If B inherits from A, which declaration is valid?D. contract C is A, B
Ch-19 : Interfaces : Interfaces in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : An interface is a contract-like declaration, written with the interface keyword, that lists function signatures without implementations. Contracts that implement it must provide those functions.

Answer : Interfaces let contracts interact with other deployed contracts using only their function signatures and address, define common standards such as ERC-20, reduce code duplication and allow different implementations to be swapped without changing the caller.

Answer : No state variables, no constructor, no modifiers, no function implementations, and all functions must be external. They also cannot inherit from contracts (only from other interfaces).

Answer : Events, custom errors, structs and enums.

Answer : By inheriting from it with is and providing every declared function, e.g. contract Counter is ICounter { function increment() external override { ... } }.

Answer : Convert its address to the interface type and call the function: ICounter(addr).increment();.

Answer : Yes, interfaces can inherit from other interfaces, but not from contracts.

Answer : An abstract contract may contain state variables, a constructor, modifiers and implemented functions, with at least one function possibly left unimplemented. An interface contains only external function declarations and no implementation or state.

Answer : Interfaces describe how a contract is called from outside; internal details are not part of an interface, so only external functions are allowed.

Answer : Yes. All functions declared in an interface are implicitly virtual, so implementing contracts can override them.

Answer : It returns a bytes4 identifier of the interface (the XOR of its function selectors). It is used with ERC-165 so a contract can report which interfaces it supports.

Answer : The application can call balanceOf, transfer and other standard functions on any ERC-20 token through IERC20, without knowing each token’s source code.

Answer : No. An interface has no implementation, so it cannot be deployed; only contracts that implement it can be deployed.

Answer : Interface names usually begin with a capital I, such as IERC20 or ICounter.

Answer : The contract is incomplete; the compiler requires it to be marked abstract, and it cannot be deployed.
MCQ Answer Key
No.QuestionCorrect Answer
1Which of these CAN be declared inside an interface?C. An event
2All functions in an interface must be:A. external
3ICounter(addr).increment() does what?B. Calls increment on the contract at addr
4Which is TRUE about interfaces and abstract contracts?D. Neither can be deployed
5An interface can inherit from:D. Only other interfaces
Ch-20 : Events : Events in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : Events are notifications emitted by a contract when something important happens. Their data is written to the transaction’s logs on the blockchain, where front ends and services can read it.

Answer : Declare it with the event keyword, e.g. event Deposited(address indexed from, uint amount);, and trigger it inside a function with emit Deposited(msg.sender, msg.value);.

Answer : In the logs of the transaction receipt, which are part of the blockchain data. It is not stored in the contract’s storage.

Answer : No. Logs are not accessible to contracts; they are meant for off-chain applications.

Answer : Log data does not need to be kept in contract storage or be readable by contracts, so the gas cost per byte is much lower than writing to storage.

Answer : Event parameters marked indexed are stored as topics, which allows applications to search and filter events by those values, e.g. all deposits from a particular address.

Answer : Up to three for a normal event (four for an anonymous event).

Answer : Indexed parameters become searchable topics; non-indexed parameters are stored in the log’s data section and returned with the event but cannot be used as filters.

Answer : They update user interfaces in real time, show transaction status, provide a permanent history for auditing and tracking, and store off-chain-only data cheaply.

Answer : With contract.getPastEvents('EventName', { filter, fromBlock, toBlock }), which returns matching events and their returnValues.

Answer : Because contracts cannot read events; any data the contract itself needs for later decisions must be kept in storage.

Answer : So that applications can efficiently filter deposits made by a specific address.

Answer : No. When a transaction reverts, all its effects, including emitted events, are discarded.

Answer : An event declared with the anonymous keyword does not store its signature as the first topic, which allows four indexed parameters and saves some gas, but it cannot be filtered by event name.

Answer : A provider that supports subscriptions, usually a WebSocket provider; plain HTTP providers can only query past events.
MCQ Answer Key
No.QuestionCorrect Answer
1Which keyword triggers an event?A. emit
2Event data is stored in:B. Transaction logs
3Up to how many parameters of a normal event can be indexed?D. Three
4Which statement about events is TRUE?C. Contracts cannot read events
5Indexed event parameters are stored as:A. Topics
Ch-21 : Error Handling : Error Handling in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : Solidity uses state-reverting exceptions: when an error occurs, all state changes made in the current call and its sub-calls are undone and an error is returned to the caller. Transactions are therefore atomic.

Answer : A transaction either completes entirely or has no effect on the state at all; partial changes are never kept.

Answer : require, revert and assert.

Answer : To validate inputs, permissions and conditions before or during execution, e.g. require(msg.value > 0, "Send Ether");. A false condition reverts with the given message.

Answer : When the decision to fail is inside more complex logic such as nested if/else blocks, or when reverting with a custom error, e.g. if (x > y) revert TooLarge(x);.

Answer : Neither is better in general: require(condition) uses a revert internally. Use require for simple guard checks and revert for complex branching or custom errors.

Answer : To check internal invariants – conditions that should never be false if the code is correct. A failing assert signals a bug and raises a Panic error with code 0x01.

Answer : No. Since 0.8.0, assert raises Panic(uint256) using the revert mechanism and the remaining gas is refunded. Before 0.8.0 it used an invalid opcode that consumed all remaining gas.

Answer : Custom errors (Solidity 0.8.4+) are declared with error, e.g. error InsufficientBalance(uint available, uint required);, and raised with revert. They cost less gas than long error strings and can carry useful data.

Answer : Error(string) is produced by require and revert with a message, indicating invalid input or conditions. Panic(uint256) is produced by assert and by compiler checks (overflow, division by zero, out-of-bounds) and indicates a bug.

Answer : 0x01 – assert failed; 0x11 – arithmetic overflow or underflow; 0x12 – division or modulus by zero (also 0x32 – array index out of bounds).

Answer : To handle failures of external function calls or contract creation without reverting the calling contract, with separate catch blocks for Error(string), Panic(uint) and low-level error data.

Answer : No. try/catch works only with external calls and contract creation with new.

Answer : No. Gas consumed up to the point of failure is still paid; only the unused remaining gas is refunded.

Answer : The final catch (bytes memory data) block, because custom errors are not Error(string) or Panic(uint); they are delivered as raw encoded error data.
MCQ Answer Key
No.QuestionCorrect Answer
1Which statement is best for validating user input at the start of a function?B. require
2A failing assert produces which error type?A. Panic(uint256)
3When a transaction reverts, the state changes it made are:D. Undone completely
4Custom errors were introduced in Solidity version:C. 0.8.4
5try/catch in Solidity can be used with:A. External calls and contract creation
Ch-22 : Modifier : Function Modifiers in Solidity

Read the notes, watch the video & take the MCQ test »

Answer : A modifier is reusable code that changes the behaviour of functions it is applied to – typically checking a condition before the function body runs and reverting if it is not met.

Answer : The _; symbol (also called the placeholder). It is replaced by the body of the function the modifier is applied to, marking where that body executes.

Answer : modifier onlyOwner() { require(msg.sender == owner, "Only owner"); _; }, applied as function withdraw() public onlyOwner { ... }.

Answer : modifier costs(uint price) { require(msg.value == price, "Wrong amount"); _; }, used as function buy() external payable costs(0.01 ether) { ... }.

Answer : The require (or revert) inside the modifier reverts the transaction, so the function body is not executed and no state changes are kept.

Answer : That code runs after the function body finishes, which is useful for clean-up such as unlocking a reentrancy guard.

Answer : The function body is never executed when that modifier is applied, because there is no place where the body is inserted.

Answer : In the order they are written in the function header, from left to right; each modifier’s _; continues to the next modifier and finally to the function body.

Answer : No. return leaves only the function body; the remaining modifier code after _; still runs.

Answer : It sets a lock before the function body and clears it afterwards, so the function cannot be re-entered while it is still running – protecting against reentrancy attacks.

Answer : Access control (onlyOwner, onlyAdmin), state checks (whenOpen, auction not ended), validating payments (costs) and reentrancy protection.

Answer : Yes. Derived contracts inherit modifiers and can override them if they are marked virtual, using the override keyword.

Answer : They keep repeated checks in one place, make functions shorter and easier to read, and reduce the chance of forgetting a check.

Answer : checkBlockAdmin(), which allows only the admin to view results and counts, and checkVoterCasting(), which stops an address from voting twice.

Answer : No. Both onlyOwner and onlyOwner() are accepted.
MCQ Answer Key
No.QuestionCorrect Answer
1In a modifier, the symbol _; represents:B. The function body being inserted
2Code written AFTER _; in a modifier runs:A. After the function body
3function f() public onlyOwner whenOpen – which modifier runs first?D. onlyOwner
4If a require inside a modifier fails:C. The whole call reverts
5Which modifier pattern protects against reentrancy?B. nonReentrant
Ch-23 : Fallback/Receive : Fallback and Receive Functions

Read the notes, watch the video & take the MCQ test »

Answer : A special unnamed function, declared with fallback() external [payable], that runs when a call does not match any function in the contract, or when Ether is sent with empty calldata and no receive function exists.

Answer : A special function declared as receive() external payable that runs when the contract receives plain Ether with empty calldata, for example via send, transfer or a wallet transfer.

Answer : receive() handles plain Ether transfers with empty calldata and must be payable. fallback() handles calls with data that match no function (and empty-calldata Ether if receive is missing) and is payable only if declared so.

Answer : It must be external and payable, with no arguments and no return value.

Answer : At most one of each.

Answer : The transfer reverts; the contract cannot accept Ether through normal transactions or calls.

Answer : The call reverts, because a fallback that is not marked payable rejects any Ether.

Answer : When Ether is sent with transfer() or send(), only 2300 gas is forwarded to the recipient’s receive or fallback function – enough to log an event but not to write to storage.

Answer : They may be called with only 2300 gas, and complex logic could fail or open security risks such as reentrancy.

Answer : An unnamed function such as function() external payable { }. Since 0.6.0 it is split into receive() and fallback().

Answer : Yes, with the form fallback(bytes calldata input) external returns (bytes memory output); otherwise msg.data can be read inside a fallback with no parameters.

Answer : Yes, in special cases such as being the recipient of selfdestruct or of block rewards/fees. Therefore address(this).balance should not be assumed to equal internally recorded deposits.

Answer : A proxy’s fallback receives every call that does not match its own functions and forwards it (usually with delegatecall) to an implementation contract, enabling upgradeable contracts.

Answer : Receiver’s fallback(), because the calldata encodes doesNotExist(), which matches no function in Receiver.

Answer : Receiver’s receive(), because the call has empty calldata and carries Ether.
MCQ Answer Key
No.QuestionCorrect Answer
1A plain Ether transfer with empty calldata to a contract that has receive() runs:A. receive()
2A call to a function name that does not exist in the contract runs:C. fallback()
3receive() must be declared as:D. external payable
4How much gas do transfer() and send() forward to the recipient?D. 2300
5If a contract has neither receive() nor a payable fallback(), sending it plain Ether will:B. Revert
Ch-24 : Payable Functions : Payable Functions and Sending Ether

Read the notes, watch the video & take the MCQ test »

Answer : A function marked payable can receive Ether with the call. The amount sent is available in msg.value (in wei) and is added to the contract’s balance.

Answer : The transaction reverts, so the Ether is not accepted.

Answer : Yes. To require payment, add a check such as require(msg.value > 0) or require(msg.value == price).

Answer : With address(this).balance, which returns the balance in wei.

Answer : address payable is an address type that has the transfer and send members for receiving Ether. A plain address is converted with payable(addr).

Answer : addr.transfer(amount), addr.send(amount) and addr.call{value: amount}("").

Answer : Both forward a fixed 2300 gas. transfer reverts automatically if sending fails; send returns false instead, so its result must be checked.

Answer : It forwards enough gas for recipients that are contracts with more complex receive logic and returns a success flag. The developer must check the flag and guard against reentrancy.

Answer : Since Solidity 0.7.0 the syntax is address.call{value: amount}(""); gas can be set with {value: amount, gas: g}.

Answer : A function first checks all conditions, then updates the contract’s own state, and only at the end interacts with other addresses (e.g. sends Ether). This prevents reentrancy attacks.

Answer : An attack in which the recipient of an external call calls back into the vulnerable function before its state is updated, for example withdrawing the same balance repeatedly.

Answer : Instead of sending Ether to many users in one transaction, the contract records how much each user is owed and each user calls withdraw() to collect it. One failing recipient cannot block the others.

Answer : They do not revert on failure; they return false. Ignoring the result could make the contract believe a payment succeeded when it did not.

Answer : receive() external payable, or a fallback() marked payable.

Answer : In wei. Amounts can be written with units such as 1 ether, 0.01 ether or 1 gwei.
MCQ Answer Key
No.QuestionCorrect Answer
1Which keyword allows a function to receive Ether?B. payable
2Which method returns false instead of reverting when sending fails?B. send
3The recommended way to send Ether in modern Solidity is:C. addr.call{value: x}("") with a success check
4In checks-effects-interactions, Ether should be sent:D. After updating state
5address(this).balance returns:A. The contract’s Ether balance in wei
Project 1 : Smart Contract Election System : Project 1 : Smart Contract for Election System

Read the notes, watch the video & take the MCQ test »

Answer : BlockAdmin is the account that deploys the contract. It can view the total votes cast and calculate and publish the winner, but it cannot change anyone’s vote.

Answer : In the constructor: blockAdmin = msg.sender;, so the deploying account becomes the admin.

Answer : struct Candidate { string candidateName; string candidateParty; uint voteCount; }, defined at file level in CandidateMaster.sol and imported into VotePanelContract.sol.

Answer : The enum candidateCode (AJIT, ASHISH, MAYANK, KUNAL, NOTA) gives readable names to candidates; converting a member with uint(...) provides the key for the candidate mapping.

Answer : uint(type(candidateCode).max) + 1. The last enum member NOTA has value 4, so the total is 5.

Answer : The checkVoterCasting() modifier loops over votersList; if msg.sender is already in the list, require fails with “You have already casted Your Voter”.

Answer : It adds msg.sender to votersList, loads the candidate from the mapping, increments voteCount and stores the updated candidate back.

Answer : It loops over all candidate codes, keeps track of the highest voteCount seen so far and stores that candidate in the public winner variable.

Answer : Because the comparison is strictly less-than, the first candidate (lower code) that reached the highest count remains the winner; the tie is not reported.

Answer : voteCountAndResult(), totalVotesCasted() and viewBlockAdmin(), all protected by checkBlockAdmin().

Answer : It loops over every address in votersList, so the gas cost of voting grows with the number of voters. A mapping(address => bool) would make the check constant-cost.

Answer : Because VotePanelContract.sol imports "contracts/CandidateMaster.sol"; the compiler can only resolve the import if a file exists at that path.

Answer : No. Every vote is a public transaction showing which candidate function each address called. Secret ballots need techniques such as commit–reveal or cryptographic voting schemes.

Answer : Use a single vote(candidateCode) function with a mapping(address => bool) for duplicate checks, and add voter registration plus a voting period (start/end or state enum) so results can only be declared after voting closes.

Answer : Votes recorded as transactions are permanent and transparent, the counting rules are public code that runs the same way on every node, and no single party can alter recorded votes.
MCQ Answer Key
No.QuestionCorrect Answer
1In the Election contract, who becomes the BlockAdmin?B. The account that deploys the contract
2uint(type(candidateCode).max) + 1 evaluates to:C. 5
3Which modifier prevents double voting?A. checkVoterCasting()
4Where are the addresses of voters stored?D. In the dynamic array votersList
5Which data structure gives a constant-cost “has voted” check?A. mapping(address => bool)
Project 2 : Smart Contract Lottery System : Project 2 : Smart Contract for Lottery System

Read the notes, watch the video & take the MCQ test »

Answer : Traditional lotteries require trust in intermediaries who sell tickets, hold funds and pick winners. A smart contract makes the rules public and executes them automatically, increasing transparency.

Answer : struct UserRecord { address useraddress; string username; uint amount; uint winningAmount; }, defined in UserRecord.sol.

Answer : checkBlockAdmin (admin only), checkTicketUser (admin cannot buy), checkTicketUserCount (one ticket per address), checkUserCount (ticket limit not exceeded) and resultStatus (result can be declared only once).

Answer : Five, because userlimit = 5 and checkUserCount requires userCount < userlimit before each purchase.

Answer : uint(keccak256(abi.encodePacked(msg.sender, block.timestamp, startvalue))) % userlimit – a hash of the caller, the block timestamp and a constant, reduced modulo 5.

Answer : It concatenates the given values into a compact byte string so they can be hashed together by keccak256.

Answer : Its inputs (caller, block timestamp, block values) are known or partly controllable, and the admin chooses when to call, so the outcome can be predicted or influenced.

Answer : Because the index is taken modulo userlimit (5) instead of the number of buyers, it may point to an unused ticket number, making the winner an empty record with the zero address.

Answer : Take the modulo of the actual number of players (userCount or players.length) and require at least one player before declaring the result.

Answer : No. TICKET_AMOUNT and totalBalance are only numbers; the purchase function is not payable and no prize is paid. The extension exercise adds real payments.

Answer : By using a verifiable random function (VRF) oracle that supplies a random number with a proof, or a commit–reveal scheme where participants commit to secrets that are revealed later.

Answer : The pull pattern lets the winner collect the prize in a separate transaction, avoiding failures or reentrancy risks during result declaration.

Answer : Because the admin controls when the result is declared; allowing the admin to play would create a conflict of interest.

Answer : That declareLotteryResult() can succeed only once; after resultDeclared is set to true, further calls revert with “Result has been Declared”.

Answer : A mapping(address => bool) hasTicket, which checks in constant time whether an address has already bought a ticket.
MCQ Answer Key
No.QuestionCorrect Answer
1In the teaching version, the winner index is calculated modulo:B. userlimit (5)
2Which function combines values into bytes before hashing?A. abi.encodePacked
3Which source gives verifiable randomness to smart contracts?C. A VRF oracle
4Which modifier stops the same address from buying two tickets?D. checkTicketUserCount
5To accept real Ether for a ticket, the purchase function must be:A. payable
Project 3 : Smart Contract Bidding/e-Auction System : Project 3 : Smart Contract for Bidding / e-Auction System

Read the notes, watch the video & take the MCQ test »

Answer : An open, ascending (English-style) auction: bids are public and each new bid must be higher than the current highest bid; the last bid wins.

Answer : ItemMaster (itemName, initBidValue, auctionResult), BiddersMaster (bidderName, bidderAddress) and AuctionRegister (userAddress, bidValue).

Answer : The account that deploys the contract (stored as auctionManager). The manager sets the auction item and declares the result, and receives the winner’s payment; the manager cannot register or bid.

Answer : Because the contract sends the winner’s Ether to the manager with auctionManager.transfer(msg.value), which requires an address payable.

Answer : It is a modifier with an argument: checkBidValue(uint bidderValue) requires the new bid to be greater than maxBidValue, otherwise the bid is rejected.

Answer : First by calling BidderRegisterMaster(name) once, then by calling MyBidding(value) with a value higher than the current maximum while the auction is open.

Answer : Because each bid must be higher than the previous one, the last recorded bid (auctionChain[chainNo - 1]) is the highest, so it becomes the winner. The item is then marked as closed.

Answer : It converts the winning bid from whole ETH to wei by multiplying by 10^18 and requires msg.value to be exactly that amount.

Answer : Because the winner sends Ether with the call; only payable functions can receive Ether.

Answer : chainNo is 0, so chainNo - 1 underflows; Solidity 0.8 checked arithmetic reverts the transaction.

Answer : Bids are only numbers, so the winner is not forced to pay. An escrow design in which bidders send Ether with each bid solves this.

Answer : It records the previous highest bid in a refunds mapping, and the out-bid user later withdraws it (pull pattern), with the balance set to zero before sending.

Answer : All function inputs and state on a public blockchain are visible. A sealed-bid auction needs a commit–reveal scheme where bids are hidden as hashes first.

Answer : A fixed end time based on block.timestamp makes the closing rule public and prevents the manager from ending the auction at a convenient moment.

Answer : gotoNextBidder() and gotoNextBlockchain() increment the regNo and chainNo counters. They are private because only the contract’s own functions should advance these counters.
MCQ Answer Key
No.QuestionCorrect Answer
1In the AuctionContract, each new bid must be:C. Greater than the current maximum
2checkBidValue(uint bidderValue) is an example of:C. A modifier with an argument
3A winning bid of 3 (ETH) requires msg.value of:D. 3 × 10^18 wei
4Which function must be payable for the winner to pay?B. transferBidAmount
5In an escrow auction, out-bid users get their Ether back by:A. Calling a withdraw/refund function
Project 4- Smart Contract Crowdfunding System : Project 4 : Smart Contract for Crowdfunding System

Read the notes, watch the video & take the MCQ test »

Answer : Crowdfunding depends on trust between donors, intermediaries and fundraisers. Recording registrations, campaigns and donations on a blockchain makes the process transparent and auditable.

Answer : Fundraiser (name, fundraiserAddress, userIdCard), Donor (name, donorAddress, userIdCard) and FundTicket (title, details, activeStatus, fundAmount, currentCollection, fundraiserAddress).

Answer : A fundraising campaign stored in the FundTicket struct, with a title, details, a target amount (fundAmount), the amount collected so far (currentCollection) and an active status.

Answer : The account that deploys the contract; the constructor stores it with fundManager = payable(msg.sender);.

Answer : It converts the ethAmount argument to wei by multiplying by 10^18 and requires msg.value to be exactly that amount.

Answer : DonateNow forwards it immediately to the Fund Manager with transfer; the manager later releases the collected amount to the fundraiser.

Answer : When currentCollection reaches or exceeds fundAmount after a donation, or when the Fund Manager releases the funds.

Answer : Both receive Ether with the call – the donor’s donation and the manager’s released amount – which is only possible in payable functions.

Answer : Only one, because the contract stores a single ticket variable and checkFundTicketStatus prevents creating a new ticket while one is active.

Answer : All blockchain data is public and permanent, so identity numbers would be exposed to everyone and could never be deleted. Personal data should be kept off-chain.

Answer : Donations are sent to the manager’s account, so the fundraiser depends on the manager to release them. Keeping funds in the contract with automatic release would remove that dependency.

Answer : Add a deadline and, if the target is not reached by then, allow each donor to withdraw their recorded donation through a refund function.

Answer : Because CrowdfundingContract.sol imports "contracts/BlockAccount.sol"; the file must exist at that path for the import to compile.

Answer : It requires msg.value sent by the manager to equal the ticket’s currentCollection converted to wei.

Answer : Store campaigns in a mapping such as mapping(uint => FundTicket) campaigns with a campaign counter, and pass the campaign ID to donate and release functions.
MCQ Answer Key
No.QuestionCorrect Answer
1In the Crowdfunding contract, donated Ether is first sent to:B. The Fund Manager
2A donor calls DonateNow(4). msg.value must be:C. 4 × 10^18 wei
3Which data should NOT be stored on a public blockchain?D. Personal ID card numbers
4Which modifier prevents a second active campaign?B. checkFundTicketStatus
5A trust-minimised improvement would keep donations:D. In the contract (escrow) until release conditions are met
Project 5- Smart Contract Badminton Tournament : Project 5 : Smart Contract for Badminton Tournament System

Read the notes, watch the video & take the MCQ test »

Answer : To record a match between two players on the blockchain – registration, points in each round and the final winner – so that the result is tamper-proof and publicly verifiable.

Answer : The account that deploys the contract. Only the referee can register players, start the match, add points and move to the next round.

Answer : PlayerBlock (playerAddress, playerName, PlayerCountry) and MatchBlock (both player addresses and each player’s points in rounds 1, 2 and 3).

Answer : enum players { PLAYER1, PLAYER2 } gives readable names to the two player slots; converted with uint(...), they act as keys of the playerList mapping.

Answer : That both players have been registered (isplayer1Init and isplayer2Init are true) before the match can start.

Answer : It creates the MatchBlock with both players’ addresses and all points set to zero, sets roundNumber to 1 and sets matchStatus to “Running”.

Answer : When a player’s points in the current round reach 21, checkForNextRound increases roundNumber and calls checkWinner; the referee can also call gotoNextRound.

Answer : If the same player reaches 21 points in rounds 1 and 2, that player wins. Otherwise round 3 is played, and the first player to reach 21 in round 3 wins.

Answer : With string.concat("Match Over : ", pname, " (WINNER)"), which joins strings (Solidity 0.8.12+).

Answer : checkRoundStatus only allows rounds 1–3, so setting 9 blocks any further scoring after the match is over.

Answer : They are internal steps of the scoring logic and should run only when called by the contract’s own functions, not directly by users.

Answer : The deuce rule: officially, at 20–20 a player must lead by two points to win the game (with a 30-point cap). The contract ends a game at exactly 21 points.

Answer : Each point is a transaction that costs gas and takes time; for real matches it may be better to record scores off-chain and store only signed final results.

Answer : Store many matches in a mapping keyed by match ID, add brackets or standings, and emit events for each point and result.

Answer : It is a view function that returns the matchStatus string – “Running” during play or “Match Over : Name (WINNER)” at the end – without costing gas when called off-chain.
MCQ Answer Key
No.QuestionCorrect Answer
1Who can add points in the BadmintonTournament contract?C. Only the Match Referee
2A game (round) ends in the contract when a player reaches:B. 21 points
3Which function joins strings to build the winner message?A. string.concat
4What prevents scoring after the match is over?D. roundNumber set to 9 with checkRoundStatus
5Player slots PLAYER1 and PLAYER2 are defined using:A. An enum
Project 6 : Smart Contract Web3.js - Jquery Cookies : Project 6 : Solidity with Web3.js and jQuery Cookies

Read the notes, watch the video & take the MCQ test »

Answer : Web3.js is a JavaScript library that lets web pages and Node.js applications communicate with an Ethereum node through JSON-RPC – reading data, sending transactions and calling smart contracts.

Answer : A provider (connection to a node or wallet), the contract’s ABI and the contract’s address.

Answer : It stores the user’s account address and name in browser cookies on the registration page so that numbersystem.html can read them and use the same address for contract calls.

Answer : Seven days, because they are created with {expires : 7}.

Answer : The page immediately redirects to numbersystem.html, so a registered user does not need to register again.

Answer : An HTTP provider pointing to Ganache at http://127.0.0.1:7545, a local development blockchain.

Answer : send() creates a signed transaction that can change contract state and costs gas; call() executes a function locally on the node without a transaction and returns its result, typically for view or pure functions.

Answer : Ganache keeps its test accounts unlocked, so the node can sign transactions for them. On real networks the user’s wallet must sign.

Answer : 16 and 64 respectively.

Answer : They read the stored digit but do not modify state, so they can be called with call() at no cost.

Answer : From the Solidity compiler – in Remix it can be copied from the compilation details after compiling the contract.

Answer : Anyone can type or edit a cookie value, so it does not prove ownership of the address. Real dApps ask the user to connect a wallet and sign transactions or messages.

Answer : By calling window.ethereum.request({ method: 'eth_requestAccounts' }), which prompts the user to connect and returns the selected account address.

Answer : Other local Ethereum development networks such as Hardhat Network or Anvil (Foundry); only the RPC URL in the provider needs to change.

Answer : A new deployment gets a new contract address (and possibly a new ABI if the code changed), so the address and ABI in numbersystem.html must be updated.
MCQ Answer Key
No.QuestionCorrect Answer
1Which Web3.js method reads a view function without creating a transaction?C. call()
2In this project, cookies store:A. The user’s account address and name
3Ganache’s default RPC URL used in the project is:D. http://127.0.0.1:7545
4To create a contract object, Web3.js needs the ABI and the:A. Contract address
5On a public network, who signs a transaction sent with send()?B. The user’s wallet
Project 7 : Smart Contract Web3.js - CarPooling dApp : Project 7 : EcoRide – A Carpooling dApp

Read the notes, watch the video & take the MCQ test »

Answer : To promote carpooling as a sustainable, cost-effective way to commute by letting drivers publish rides and passengers find and book seats, with ride and booking records kept on a blockchain.

Answer : RegiterUsers (user accounts), PublishRide (published rides), RideBooking (bookings) and PublishRideBookingList (a combined ride-and-booking record for listings).

Answer : With counters rideKey and bookingKey that start at 1 and increase after each new ride or booking; the records are stored in mappings at index key − 1.

Answer : nop is the number of passenger seats offered in a ride; nopstatus is the number of seats already booked.

Answer : It computes the free seats (nop − nopstatus). If they are at least the requested seats, it updates nopstatus, marks the ride full when no seats remain, calculates the amount (seats × charges) and stores a new RideBooking.

Answer : They loop over stored rides, copy matching rides into a memory array of PublishRide structs and return the array together with the number of matches.

Answer : Search by location (from/to), by date and by vehicle type, plus listings of a driver’s rides, a passenger’s rides and booked rides for both.

Answer : No. ridepaymentupdates only sets paymentstatus to true. Automating payments would require payable booking functions and an escrow mechanism.

Answer : The HTML/JavaScript front end uses Web3.js to call the contract’s functions – sending transactions for registration, rides and bookings, and calling view functions for searches.

Answer : Any account can pass someone else’s address and act on their behalf. Using msg.sender as the acting user and checking ownership prevents this.

Answer : Blockchain data is public and permanent, so personal contact details would be exposed to everyone and could never be removed.

Answer : Each search loops over all rides; with many rides the loop needs more computation and can hit gas limits even for view calls. Off-chain indexing of events is the usual solution.

Answer : Events such as RidePublished and RideBooked let the front end and indexing services update screens and notify users in real time without repeatedly scanning contract storage.

Answer : Automated payments, route matching and navigation, ratings and reviews, a carbon-impact dashboard with rewards, real-time notifications and privacy-preserving identity verification.

Answer : Function return values of reference types must be in memory; the search builds a temporary array of matching structs in memory and returns it to the caller.
MCQ Answer Key
No.QuestionCorrect Answer
1In EcoRide, which field counts seats already booked on a ride?C. nopstatus
2The amount for a booking is calculated as:D. Seats × ride charges
3Search functions return results as:D. A memory array of structs plus a count
4Which improvement prevents one user from cancelling another user’s ride?A. Using msg.sender and ownership checks
5What does ridepaymentupdates() do in the teaching version?B. Sets the booking’s payment status flag to true