Solidity Basic Solidity (Web Dev) 4 — Questions and Answers
Question 1: What does 'assert()' do differently from 'require()' in Solidity?
- assert() refunds unused gas; require() does not
- assert() consumes all remaining gas on failure; require() refunds unused gas (Correct answer)
- assert() is used for input validation; require() is for invariants
- There is no difference
Correct answer: assert() consumes all remaining gas on failure; require() refunds unused gas
assert() consumes all remaining gas and is for invariant checks; require() refunds gas and is for preconditions.
Question 2: In Solidity, what is 'abi.encode()' primarily used for?
- Encrypting data before storage
- ABI-encoding values into bytes for cross-contract calls or hashing (Correct answer)
- Compressing storage variables
- Converting uint to string
Correct answer: ABI-encoding values into bytes for cross-contract calls or hashing
abi.encode() serializes values into ABI-encoded bytes, commonly used for hashing or low-level calls.
Question 3: Which modifier prevents a function from being re-entered before it finishes execution?
- payable
- nonReentrant (Correct answer)
- onlyOwner
- pure
Correct answer: nonReentrant
The nonReentrant modifier (typically from OpenZeppelin's ReentrancyGuard) blocks recursive external calls.
Question 4: What does 'keccak256(abi.encodePacked(a, b))' compute in Solidity?
- The SHA-256 hash of a and b
- The Keccak-256 hash of the tightly packed encoding of a and b (Correct answer)
- The MD5 hash of a and b
- The BLAKE2 hash of a and b
Correct answer: The Keccak-256 hash of the tightly packed encoding of a and b
keccak256 computes the Keccak-256 hash, and encodePacked tightly packs the inputs without padding.
Question 5: What is the maximum number of indexed parameters an event can have in Solidity?
- 1
- 2
- 3 (Correct answer)
- 4
Correct answer: 3
Solidity events support up to 3 indexed parameters, which are stored as topics in the transaction log.
Question 6: Which Solidity visibility specifier makes a function accessible ONLY from within the same contract (not derived contracts)?
- internal
- private (Correct answer)
- external
- restricted
Correct answer: private
Private functions are only callable within the contract that defines them, not from derived contracts.
Question 7: What does the 'immutable' keyword do in Solidity?
- Makes a variable settable once in the constructor and then read-only (Correct answer)
- Makes a variable settable only at declaration
- Prevents a variable from being read externally
- Makes a function unable to modify state
Correct answer: Makes a variable settable once in the constructor and then read-only
Immutable variables can be assigned in the constructor only and are stored in bytecode, not storage.
What does 'assert()' do differently from 'require()' in Solidity?