Solidity Interview Questions and Answers For fresher

Beginner-Level Questions

1. What is Solidity?

Solidity is a statically-typed, high-level programming language designed for developing smart contracts that run on the Ethereum Virtual Machine (EVM). It supports features like inheritance, libraries, and complex user-defined types.

2. What is a Smart Contract?

A smart contract is a self-executing contract with the terms of the agreement directly written into code. It automatically enforces and executes transactions when predefined conditions are met.

3. What are the key data types in Solidity?

Common data types in Solidity include:

  • uint: Unsigned integers.
  • int: Signed integers.
  • address: Holds an Ethereum address.
  • bool: Boolean values.
  • string: Strings of text.
  • bytes: Fixed or dynamic-size byte arrays.
  • mapping: Key-value pairs.
  • struct: Custom data structures.

4. What is a pragma directive in Solidity?

The pragma directive is used to specify the compiler model or features. Example:

pragma solidity ^0.8.0;

5. What is the msg object in Solidity?

The msg object provides metadata about the current transaction, including:

  • msg.sender: Address of the caller.
  • msg.value: Amount of Ether sent with the call.
  • msg.data: Data payload of the transaction.

Intermediate-Level Questions

6. What is the difference between memory and storage in Solidity?

memory: Temporary storage for function execution, cleared after the function call.
storage: Permanent storage on the blockchain, persists across function calls.

7. Explain the concept of “fallback function” in Solidity.

A fallback function is a special function that executes when no other function matches the called signature or if Ether is sent without calldata. Example:


fallback() external payable {
    // Logic for handling unmatched calls or Ether transfers
}
    

8. What is the difference between require and assert?

require: Used to validate user inputs and conditions. Refunds gas.
assert: Used to check for invariants. Consumes all remaining gas.

9. How does the modifier keyword work in Solidity?

Modifiers are used to change the behavior of a function. Example:


modifier onlyOwner() {
    require(msg.sender == owner, "Not the owner");
    _;
}

function secureFunction() public onlyOwner {
    // Logic
}
    

10. What is selfdestruct in Solidity?

The selfdestruct function removes a contract from the blockchain and sends its balance to a specified address. Example:

selfdestruct(payable(owner));

Advanced-Level Questions

11. What are reentrancy attacks, and the way can they be prevented?

Reentrancy attack: An attacker repeatedly calls a vulnerable function before the initial execution completes.
Prevention techniques:

  • Use the Checks-Effects-Interactions pattern.
  • Use ReentrancyGuard from OpenZeppelin.

12. What is the purpose of events in Solidity?

Events are used to log statistics at the blockchain, enabling off-chain programs to listen and react to them. Example:


event Transfer(address indexed from, address indexed to, uint256 value);

function transfer(address _to, uint256 _value) public {
    emit Transfer(msg.sender, _to, _value);
}
    

13. What is an interface in Solidity?

An interface defines the structure of a contract without implementation, enabling interaction with other contracts. Example:


interface Token {
    function transfer(address recipient, uint256 amount) external;
}
    

14. How can a contract be upgraded in Solidity?

Upgradeable contracts can be implemented using:

  • Proxy pattern (delegate calls).
  • OpenZeppelin’s Upgradeable Contracts library.

15. What is gas in Ethereum?

Gas is a measure of computational effort required to execute operations at the Ethereum network. Users pay gas fees in Ether to incentivize miners to procedure transactions.

Scenario-Based Questions

16. How would you implement a basic ERC-20 token in Solidity?

Refer to the ERC-20 standard and use OpenZeppelin’s library to quickly create compliant tokens.

17. Write a function to safely send Ether from a contract.


function sendEther(address payable recipient, uint256 amount) public {
    require(address(this).balance >= amount, "Insufficient balance");
    (bool success, ) = recipient.call{value: amount}("");
    require(success, "Transfer failed");
}
    

18. How would you handle storing large datasets in Solidity?

Use external answers like IPFS or Arweave for off-chain storage and save best the hash or reference within the agreement.

Tips for Interview Preparation

  • Hands-on Practice: Build small projects like token contracts, DApps, and staking mechanisms.
  • Study Standards: Understand standards like ERC-20, ERC-721, and ERC-1155.
  • Security Best Practices: Familiarize yourself with Solidity pitfalls like reentrancy, integer overflows, and gas optimization.

TOPIC WISE

Basic Questions

1. What is Solidity?

Solidity is a high-level, statically typed programming language for writing smart contracts on Ethereum and EVM-compatible blockchains.

2. What are smart contracts?

Smart contracts are self-executing contracts with terms directly written in code, enabling automated execution without intermediaries.

3. What is the difference between EVM and Solidity?

EVM is the runtime environment for executing smart contracts, while Solidity is the programming language used to write them.

4. What are the key features of Solidity?

Statically typed, inheritance, libraries, modifiers, events, and complex data types like mappings and structs.

5. What is the latest version of Solidity (as of now)?

Check Solidity’s official documentation for the latest version, as it updates frequently.

Data Types

6. What are the main data types in Solidity?

uint, int, bool, address, string, bytes, mapping, array, and struct.

7. What is the difference between uint and int?

uint represents unsigned integers (non-negative), while int represents signed integers (negative and positive).

8. What is the purpose of address data type?

Stores Ethereum addresses and provides functionalities like balance checks and contract calls.

9. How is string different from bytes?

string is used for textual data, while bytes is for binary data.

10. What are structs in Solidity?

Custom data types for grouping variables. Example:


struct Person {
    string name;
    uint age;
}
    

Modifiers

11. What are modifiers in Solidity?

Modifiers are used to change the behavior of a function. Example:


modifier onlyOwner() {
    require(msg.sender == owner, "Not the owner");
    _;
}
    

12. Can you chain modifiers?

Yes, multiple modifiers can be used on a function.

13. What is the role of _ in modifiers?

_ indicates where the function body will execute in the modifier.

14. How to write a custom modifier?

Example:


modifier validAddress(address _addr) {
    require(_addr != address(0), "Invalid address");
    _;
}
    

15. How do you restrict a function to certain users?

Use a modifier with msg.sender checks.

Control Structures

16. What is if-else in Solidity?

Conditional branching like other languages. Example:


if (x > 10) { ... } else { ... }
    

17. Does Solidity support loops?

Yes, for, while, and do-while.

18. How do loops affect gas costs?

Gas increases linearly with loop iterations, so avoid large loops.

19. What is the alternative to loops for efficiency?

Use mappings or external computation off-chain.

20. What happens if a loop runs indefinitely?

The transaction will fail when gas runs out.

Functions

21. What are view and pure functions?

view: Reads blockchain state without modifying it.
pure: Neither reads nor modifies blockchain state.

22. What is the default visibility of a function?

internal.

23. What are constructors?

Functions executed only once during contract deployment.

24. Can a contract have multiple constructors?

No, Solidity supports only one constructor.

25. What is the payable function?

Allows the contract to receive Ether. Example:


function deposit() public payable { ... }
    

Memory Management

26. What is the difference between memory and storage?

memory: Temporary, used for function execution.
storage: Persistent, used for storing state variables.

27. What is calldata?

A non-modifiable, temporary area for external function arguments.

28. What is stack?

A small data area for computations within a function.

29. Which is more gas-efficient: memory or storage?

memory is more efficient than storage.

30. When should you use memory over storage?

For temporary data that does not need persistence.

Events

31. What are events?

Mechanism to log data on the blockchain for external applications.

32. What is the syntax of an event?

Example:


event Transfer(address indexed from, address indexed to, uint256 amount);
    

33. What is indexed in events?

Allows filtering specific event parameters in logs.

34. How many parameters can be indexed in an event?

Up to three.

35. How are events different from function calls?

Events are write operations and do not return values.

Error Handling

36. What are the main error-handling mechanisms?

require , assert , and revert.

37. What is the difference between require and assert?

require: Used for input validation, refunds gas.

assert: Checks invariants, consumes all gas.

38. What is revert?

Rolls back state changes and provides an error message.

39. When should you use require?

For user input validation.

40. When should you use assert?

For logic and invariant checks.

Security

41. What are reentrancy attacks?

A vulnerability where an external call re-enters the contract and manipulates state.

42. How do you prevent reentrancy?

Use OpenZeppelin’s ReentrancyGuard or checks-effects-interactions pattern.

43. What is integer overflow and underflow?

Mathematical operations exceeding or going below storage limits.

44. How do you prevent overflows?

Use Solidity 0.8+ or OpenZeppelin’s SafeMath.

45. What is access control?

Mechanism to restrict function execution based on roles or addresses.

Advanced Topics

46. What is a fallback function?

Executes when no other function matches the call or Ether is sent without calldata.

47. What is a receive function?

A simpler fallback function exclusively for receiving Ether.

48. What are upgradeable contracts?

Contracts designed to allow modifications post-deployment, typically using proxy patterns.

49. What is delegatecall?

Executes code in another contract while preserving the caller’s context.

50. How do you use interfaces in Solidity?

Example:


interface Token {
    function transfer(address recipient, uint256 amount) external;
}
    



1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *