BTA CBDE study materials
BTA CBDE study resources

BTA CBDE practice questions

One question at a time. Build your BTA CBDE understanding.

First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1Ethereum Blockchain Development Fundamentals

Which Ethereum client component is responsible for executing transactions and maintaining the world state, as opposed to reaching consensus with other nodes?

  1. The consensus client
  2. The beacon node
  3. The validator client
  4. The execution client Correct answer.

Explanation

After the Merge, Ethereum nodes run two software layers. The execution client processes transactions, runs the EVM, and stores state and receipts, while the consensus client handles proof-of-stake agreement and block gossip. The two communicate over an authenticated engine API.

Question 2Ethereum Blockchain Development Fundamentals

In Solidity, which data location must be used for a function parameter that is a dynamically sized array passed to an external function and intended to avoid copying?

  1. stack
  2. memory
  3. calldata Correct answer.
  4. storage

Explanation

External function parameters that are arrays or structs can be declared calldata, which reads directly from the transaction input without copying. Memory creates a temporary copy, and storage refers to persistent contract state, which is not valid for external parameters.

Question 3Ethereum Blockchain Development Fundamentals

A contract stores a mapping(address => uint256) named balances. What does calling balances[msg.sender] return for an address that has never been written to?

  1. It reverts because the key is absent
  2. It returns the maximum uint256 value
  3. It returns zero Correct answer.
  4. It returns the value stored at slot zero

Explanation

Mappings in Solidity have no notion of key existence; every possible key maps to a value. Unset entries read as the type's default value, which for uint256 is zero. This differs from a hash map in typical languages, where a missing key raises an error.

Question 4Ethereum Blockchain Development Fundamentals

Which opcode is used by a Solidity contract to read the ETH balance of an arbitrary address?

  1. EXTCODECOPY
  2. CALLVALUE
  3. BALANCE Correct answer.
  4. SELFBALANCE

Explanation

The BALANCE opcode returns the ether balance of the address supplied on the stack. SELFBALANCE only returns the current contract's own balance and is cheaper, while CALLVALUE reports the wei sent with the current call. EXTCODECOPY copies another account's bytecode.

Question 5Ethereum Blockchain Development Fundamentals

What is the primary purpose of the EVM's gas mechanism?

  1. To compress state before storage
  2. To price computation and bound the work a transaction can perform Correct answer.
  3. To order transactions by arrival time
  4. To encrypt transaction payloads

Explanation

Gas assigns a cost to each opcode so that computation and storage have a measurable price. It caps the total work any single transaction can do, preventing infinite loops and denial-of-service, and it lets users bid for block space. Gas has nothing to do with encryption or ordering by time.

Question 6Ethereum Blockchain Development Fundamentals

A transaction is sent with gasLimit 100000 but the execution consumes 60000 gas. How much gas is charged to the sender?

  1. 100000, with the unused portion refunded in ETH
  2. 60000 plus a fixed penalty of 40000
  3. 60000, and the unused 40000 is never charged Correct answer.
  4. The block gas limit divided by the number of transactions

Explanation

The sender is charged only for gas actually consumed, so unused gas is not billed. The gas limit is an upfront affordability check and a safety ceiling, not a charge. Note that a portion of the base fee is burned, but the unused gas itself is simply not paid for.

Question 7Ethereum Blockchain Development Fundamentals

Which address format does an Ethereum externally owned account use?

  1. A checksum-free 16-byte identifier assigned at account creation
  2. A 20-byte value derived from the SHA-256 hash of the private key
  3. A 32-byte value equal to the raw public key
  4. A 20-byte value derived from the last 20 bytes of the Keccak-256 hash of the public key Correct answer.

Explanation

An EOA address is the last 20 bytes of the Keccak-256 hash of the uncompressed public key, excluding the 0x04 prefix. The private key is never hashed to form an address, and addresses are 20 bytes, not 32 or 16.

Question 8Ethereum Blockchain Development Fundamentals

What distinguishes a contract account from an externally owned account on Ethereum?

  1. A contract account has a nonce that always stays at zero
  2. A contract account is controlled by a private key held by its deployer
  3. A contract account has associated bytecode that executes when it is called Correct answer.
  4. A contract account cannot hold ether

Explanation

Contract accounts carry code, and calls to them trigger execution of that code in the EVM. EOAs are controlled by private keys and have no code. Both account types can hold ether, and contract accounts do maintain a nonce used when they create contracts.

Question 9Ethereum Blockchain Development Fundamentals

In the Ethereum transaction envelope introduced by EIP-1559, what are maxPriorityFeePerGas and maxFeePerGas used for?

  1. They set the block gas limit and the transaction gas limit
  2. They specify the calldata size and the access list
  3. They cap the total fee and specify the tip paid to the block proposer Correct answer.
  4. They define the nonce range and the chain ID

Explanation

A type-2 transaction declares the maximum total fee per gas it will pay and the priority fee, or tip, offered to the proposer. The effective priority fee is the smaller of the tip and the difference between maxFeePerGas and the block base fee. The base fee portion is burned.

Question 10Ethereum Blockchain Development Fundamentals

A developer wants to read the ETH balance of a contract from off-chain JavaScript without spending gas. Which approach is appropriate?

  1. Send a transaction calling a payable function
  2. Use eth_call against a view function or provider getBalance Correct answer.
  3. Deploy a new contract that logs the balance
  4. Use eth_sendRawTransaction with a zero gas price

Explanation

Read-only queries do not require a transaction. eth_call simulates execution against current state without mining, and provider helpers such as getBalance query the node directly. Sending a transaction costs gas and changes state.

Question 11Ethereum Blockchain Development Fundamentals

What does the nonce of an externally owned account guarantee?

  1. That the account's code cannot be modified
  2. That gas prices stay constant across blocks
  3. That the account's balance cannot fall below zero
  4. That transactions from that account are processed in order and each is executed at most once Correct answer.

Explanation

Each EOA transaction carries a sequential nonce, and nodes reject a transaction whose nonce has already been used or is not the next expected value. This enforces ordering and prevents replay of the same signed transaction. Balance checks and gas pricing are separate concerns.

Question 12Ethereum Blockchain Development Fundamentals

Which Solidity visibility modifier allows a function to be called only from within the same contract or derived contracts?

  1. public
  2. private
  3. external
  4. internal Correct answer.

Explanation

Internal functions are callable from the defining contract and from contracts that inherit from it. Private restricts calls to the defining contract only, while public and external allow outside calls. Choosing the narrowest visibility reduces attack surface.

Question 13Ethereum Blockchain Development Fundamentals

What is the effect of the payable modifier on a Solidity function?

  1. It causes the function to be executed at deploy time
  2. It makes the function's parameters immutable
  3. It allows the function to receive ether with a call Correct answer.
  4. It restricts the function to the contract owner

Explanation

A function must be marked payable to accept ether; otherwise a call that sends value reverts. Payable has no effect on parameter mutability, deployment timing, or caller identity. The receive and fallback functions must also be payable to accept plain transfers.

Question 14Ethereum Blockchain Development Fundamentals

A contract function performs a call to an untrusted external address before updating its own balance record. Which vulnerability does this pattern most directly invite?

  1. Front-running of the deployment
  2. Integer overflow
  3. Reentrancy Correct answer.
  4. Storage collision in a proxy

Explanation

If state is updated after an external call, the callee can re-enter the function before the update lands and repeat the withdrawal. The checks-effects-interactions pattern and reentrancy guards prevent this. Overflow is handled by Solidity 0.8 arithmetic checks, and the other options concern different mechanisms.

Question 15Ethereum Blockchain Development Fundamentals

Which statement about Solidity events is accurate?

  1. Events permanently modify contract storage slots
  2. Events are readable by other contracts during execution
  3. Events can only be emitted by the constructor
  4. Events are stored in transaction logs and are not accessible to contracts at runtime Correct answer.

Explanation

Emitting an event writes to the transaction receipt logs, which are cheap compared with storage and are not readable by contracts during execution. Off-chain indexers consume them. Indexed parameters become log topics, and up to three may be indexed in a normal event.

Question 16Ethereum Blockchain Development Fundamentals

What is the role of the ABI in Ethereum development?

  1. It stores the contract's state trie
  2. It defines how function calls and return values are encoded and decoded between clients and contracts Correct answer.
  3. It determines the gas price for each opcode
  4. It encodes the contract's bytecode for deployment

Explanation

The application binary interface specifies function selectors, argument types, and return encodings, allowing tools to build calldata and decode results. The bytecode is separate, and the ABI does not store state or set gas costs. It is usually generated by the compiler as JSON.

Question 17Ethereum Blockchain Development Fundamentals

Which hashing function is used to compute the four-byte function selector in a Solidity contract call?

  1. Keccak-256 of the signature, taking the first four bytes Correct answer.
  2. SHA-256 of the signature
  3. MD5 of the signature
  4. RIPEMD-160 of the signature, taking the last four bytes

Explanation

A selector is the first four bytes of the Keccak-256 hash of the canonical function signature, such as transfer(address,uint256). Ethereum uses Keccak-256 rather than the standardized SHA3-256, and these differ in padding. MD5 and RIPEMD-160 are not used for selectors.

Question 18Ethereum Blockchain Development Fundamentals

A developer needs a value fixed at construction time that cannot be changed later and is cheaper to read than a storage variable. Which declaration fits?

  1. A private storage variable with a setter
  2. A public constant initialized from a constructor argument
  3. An immutable variable assigned once in the constructor Correct answer.
  4. A mapping entry written during deployment

Explanation

Immutable variables are assigned once at construction and their values are embedded in the deployed bytecode, so reads avoid storage access. Constant variables must be initialized at declaration and cannot depend on constructor arguments. Both are cheaper to read than storage.

Question 19Ethereum Blockchain Development Fundamentals

What does the DELEGATECALL opcode do when contract A calls contract B with it?

  1. It runs B's code in A's storage and address context Correct answer.
  2. It creates a new contract at B's address
  3. It transfers ether from A to B
  4. It copies B's code into A's storage permanently

Explanation

DELEGATECALL executes the callee's code while preserving the caller's storage, address, and balance context, and it also preserves msg.sender and msg.value. It is the basis of proxy upgrade patterns. It does not move ether or deploy a contract.

Question 20Ethereum Blockchain Development Fundamentals

Which pattern allows a contract's logic to be replaced while its address and storage persist?

  1. A contract that redeploys itself with CREATE2 each time
  2. A proxy that forwards calls with DELEGATECALL to an implementation address Correct answer.
  3. A self-destruct call in the constructor
  4. An event that signals a new implementation

Explanation

In an upgradeable proxy, the proxy holds state and delegates execution to an implementation contract whose address can be changed. Because DELEGATECALL preserves the proxy's storage context, state survives upgrades. Storage layout must be preserved between implementations to avoid corruption.

Question 21Ethereum Blockchain Development Fundamentals

Which is true about the block base fee under EIP-1559?

  1. It is set by the transaction sender
  2. It is burned and adjusts based on how full the previous block was Correct answer.
  3. It is fixed at one gwei forever
  4. It is paid to the block proposer as a tip

Explanation

The protocol computes the base fee from the previous block's gas usage relative to the target and burns it. Only the priority fee reaches the proposer. This makes the base fee predictable and ties it to demand rather than to sender choice.

Question 22Ethereum Blockchain Development Fundamentals

In Solidity, what happens when an assert statement fails at runtime?

  1. It refunds the remaining gas to the sender
  2. It returns false to the caller without reverting
  3. It emits an event and continues execution
  4. It consumes all remaining gas in the call and reverts Correct answer.

Explanation

A failing assert triggers an invalid opcode, which reverts and consumes all remaining gas in the frame. Require is intended for input validation and refunds unused gas, while assert signals an invariant that should never be violated. Custom errors and revert strings behave like require.

Question 23Ethereum Blockchain Development Fundamentals

Which tool is commonly used to compile Solidity and generate deployment artifacts such as ABI and bytecode?

  1. geth
  2. ganache
  3. solc Correct answer.
  4. metamask

Explanation

solc is the Solidity compiler; it produces bytecode, the ABI, and metadata, and frameworks wrap it. Geth is an execution client, Ganache is a local test chain, and MetaMask is a wallet. Only the compiler generates artifacts from source.

Question 24Ethereum Blockchain Development Fundamentals

A contract uses block.timestamp to decide a lottery winner. Why is this considered risky?

  1. Timestamps cannot be read by contracts
  2. Proposers have limited influence over the timestamp and can bias outcomes within protocol bounds Correct answer.
  3. Timestamps cost more gas than block numbers
  4. Timestamps are always zero on mainnet

Explanation

A block proposer can nudge the timestamp within the allowed drift, so outcomes depending on it are partially manipulable. For randomness, commit-reveal schemes or verifiable randomness oracles are preferred. Timestamps are readable and nonzero, and gas cost is not the core issue.

Question 25Ethereum Blockchain Development Fundamentals

What is the purpose of the checks-effects-interactions pattern?

  1. To reduce gas by batching writes
  2. To ensure that events are emitted before state changes
  3. To update contract state before making external calls so reentrant calls see consistent state Correct answer.
  4. To guarantee that external calls always succeed

Explanation

By performing all state updates before interacting with external addresses, the contract ensures any reentrant call observes the already-updated state. This blocks classic reentrancy drains. The pattern is about ordering for safety, not gas savings or guaranteed call success.

Question 26Ethereum Blockchain Development Fundamentals

Which unit is the smallest denomination of ether in the Ethereum protocol?

  1. Wei Correct answer.
  2. Ether
  3. Gwei
  4. Finney

Explanation

Ether is divisible into many denominations, and the smallest indivisible unit defined by the protocol is the wei. One ether equals 10^18 wei, so every on-chain balance is ultimately an integer count of wei. Gwei and finney are simply larger multiples used for convenience.

Question 27Ethereum Blockchain Development Fundamentals

Which value does the EVM return when a call is made to an address that has no deployed code?

  1. It reverts with an invalid opcode
  2. It returns success with empty return data Correct answer.
  3. It throws a compilation error
  4. It consumes all forwarded gas

Explanation

The EVM treats an account with no code as an ordinary value transfer target, so the call succeeds and returns no data. This is why low-level calls must check both the success flag and the code length when interacting with expected contracts. It also underlies the risk of calling a mistyped address.

Question 28Ethereum Blockchain Development Fundamentals

What does the EVM do with the remaining gas when a transaction's execution finishes successfully before consuming the full gas limit?

  1. It rolls the remainder into the next transaction
  2. It burns the remainder
  3. It transfers the remainder to the miner
  4. It refunds the remainder to the sender Correct answer.

Explanation

The sender is charged only for gas actually consumed, plus any refund adjustments, so unused gas is returned to the sender's balance. The gas limit therefore acts as a cap on spend rather than a fixed charge. This is why setting a generous limit is safe when the sender has sufficient balance.

Question 29Ethereum Blockchain Development Fundamentals

Which component of a transaction's signature determines the sender's address on Ethereum?

  1. The ECDSA signature over the transaction hash Correct answer.
  2. The gas price field
  3. The chain ID field
  4. The recipient address

Explanation

The sender is recovered cryptographically from the ECDSA signature and the signed transaction hash, so no sender field is stored. This binds the transaction to the holder of the private key. Any tampering with the payload invalidates the recovery.

Question 30Ethereum Blockchain Development Fundamentals

A developer wants to store a mapping from user address to a struct in Solidity. Which declaration is valid?

  1. mapping(address => MyStruct) memory records;
  2. mapping(address => MyStruct) constant records;
  3. mapping(address => MyStruct) calldata records;
  4. mapping(address => MyStruct) public records; Correct answer.

Explanation

Mappings may only be declared as storage variables, and state variables default to storage, so the plain declaration with a visibility keyword is correct. Mappings cannot live in memory or calldata and cannot be marked constant. Marking it public generates a getter for lookups.

Question 31Ethereum Blockchain Development Fundamentals

A contract holds 10 ether and a function executes `payable(msg.sender).transfer(5 ether)`. What happens if the recipient's fallback reverts?

  1. The ether is queued for a later block
  2. The transfer fails but the outer call continues
  3. The ether is sent with half the gas
  4. The transfer fails and the whole transaction reverts Correct answer.

Explanation

The transfer function forwards a fixed 2300 gas stipend and reverts the entire call chain when the recipient's code fails. This all-or-nothing behavior protects the sender's accounting but can also block payouts to contracts with expensive fallbacks. Developers often prefer call with explicit gas handling for that reason.

Question 32Ethereum Blockchain Development Fundamentals

Which Solidity data location must be used for a dynamic array passed as a parameter to an external function?

  1. memory
  2. storage
  3. calldata Correct answer.
  4. stack

Explanation

External function parameters of dynamic types are read from transaction calldata, so calldata is the required and cheapest location. Memory copies would cost extra gas and are not permitted for external parameters of reference types. Public functions, by contrast, may use memory because they are called internally as well.

Question 33Ethereum Blockchain Development Fundamentals

A contract calls `address.call{value: 1 ether}("")` and ignores the returned boolean. What is the main risk?

  1. The call consumes no gas
  2. The ether is automatically refunded
  3. A failed send goes unnoticed and state diverges from reality Correct answer.
  4. The compiler rejects the code

Explanation

Low-level calls return a success flag instead of reverting, so ignoring it lets execution continue after a failed transfer. The contract may then record a payment that never happened. Best practice is to check the flag and revert explicitly.

Question 34Ethereum Blockchain Development Fundamentals

Which Solidity construct restricts a function so it can only be executed when the caller holds a specific role recorded in storage?

  1. A modifier that checks a stored role mapping Correct answer.
  2. An event emission
  3. A pure function
  4. A view function

Explanation

Access control is implemented with modifiers that read a stored mapping or role registry and revert when the check fails. This pattern centralizes the authorization rule and applies it consistently across functions. View and pure functions cannot enforce state-changing permissions because they do not alter state.

Question 35Ethereum Blockchain Development Fundamentals

A developer needs a value derived deterministically from on-chain data that all nodes agree on. Which source is appropriate?

  1. A random number from the local clock
  2. block.prevrandao combined with block data Correct answer.
  3. The developer's off-chain API response
  4. The user's IP address

Explanation

Consensus-critical values must be reproducible by every node from the block itself, so block fields such as prevrandao, timestamp, and blockhash are usable. Off-chain inputs and environment data are not part of consensus and would cause divergence. Even block data is only pseudorandom and can be influenced by block producers.

Question 36Ethereum Blockchain Development Fundamentals

Which statement describes the effect of the `immutable` keyword on a state variable?

  1. Its value is stored in the contract bytecode after deployment Correct answer.
  2. Its value is stored only in event logs
  3. Its value is recomputed on every read
  4. Its value can be changed by the owner at any time

Explanation

Immutable variables are assigned once during construction and then embedded directly in the deployed bytecode. Reads avoid a storage slot access, which makes them cheaper than ordinary state variables. They cannot be modified after deployment.

Question 37Ethereum Blockchain Development Fundamentals

A contract must send ether to many recipients in one transaction. Which design consideration matters most?

  1. Making the function payable so it can receive funds
  2. Emitting one event per recipient to reduce gas
  3. Using transfer for every recipient to guarantee safety
  4. Bounding the loop so total gas stays under the block gas limit Correct answer.

Explanation

Loops over unbounded arrays can exceed the block gas limit and make the function permanently uncallable. Pull-payment patterns or paginated batches keep each transaction within limits. Fixed-gas transfer calls also risk reverting on recipients with complex fallbacks.

Question 38Ethereum Blockchain Development Fundamentals

What is the purpose of the `receive` function in a Solidity contract?

  1. To handle calls that include function calldata
  2. To handle plain ether transfers sent with empty calldata Correct answer.
  3. To replace the constructor
  4. To define the contract's fallback ABI

Explanation

The receive function is invoked when a contract is sent ether with empty calldata, and it must be marked payable. Calls carrying calldata that match no function go to the fallback instead. A contract without receive can still accept ether through a payable fallback.

Question 39Ethereum Blockchain Development Fundamentals

A contract's storage layout is changed by inserting a new variable before existing ones in an upgradeable proxy setup. What is the consequence?

  1. The proxy automatically migrates old data
  2. Storage reads return values belonging to the wrong variables Correct answer.
  3. Only events are affected
  4. The compiler rejects the upgrade

Explanation

Upgradeable contracts rely on identical storage slot layouts across implementations, so inserting a variable shifts every later slot. Existing data is then interpreted as the wrong type or variable, corrupting state. New variables must be appended and gaps reserved for future additions.

Question 40Ethereum Blockchain Development Fundamentals

A contract computes a commitment as `keccak256(abi.encodePacked(a, b))` where both are dynamic types. Why can this be unsafe?

  1. Concatenation without length prefixes allows ambiguous collisions Correct answer.
  2. The hash is truncated to 20 bytes
  3. keccak256 is deprecated for dynamic types
  4. abi.encodePacked reverts on strings

Explanation

Packed encoding omits length separators, so different combinations of dynamic values can produce identical byte sequences. Hashing that encoding can therefore yield the same commitment for distinct inputs. Using abi.encode with fixed-length types avoids the ambiguity.

Question 41Smart Contract Development with Solidity

In Solidity, which keyword makes a function parameter passed by reference while forbidding any modification of the referenced data inside the function?

  1. memory
  2. storage
  3. calldata Correct answer.
  4. constant

Explanation

The calldata keyword marks reference-type parameters that live in the non-modifiable call data area, so any assignment to them is a compile error. It is also cheaper than memory because no copy is made. Memory creates a mutable copy, and storage refers to persistent state.

Question 42Smart Contract Development with Solidity

What does the Solidity compiler emit for a public state variable declared as uint256 total;?

  1. A getter function named total() that returns the value Correct answer.
  2. A private function callable only from the constructor
  3. An event named total that fires on each write
  4. A modifier that guards the variable against writes

Explanation

Public state variables get an automatically generated getter with the same name that returns the stored value. For mappings and arrays the getter takes the key or index as arguments. The variable is still readable directly inside the contract without calling the getter.

Question 43Smart Contract Development with Solidity

Which unit suffix does Solidity define for one billion wei?

  1. szabo
  2. finney
  3. ether
  4. gwei Correct answer.

Explanation

Solidity defines gwei as 10^9 wei, szabo as 10^6 wei, finney as 10^15 wei and ether as 10^18 wei. These suffixes can be appended to numeric literals to express amounts. Gwei is commonly used to denominate gas prices.

Question 44Smart Contract Development with Solidity

Which statement about Solidity mappings is correct?

  1. They store a length that can be read on chain
  2. They have no length and cannot be enumerated Correct answer.
  3. They can be iterated with a for loop over their keys
  4. They can be declared with a dynamic array as key type

Explanation

Mappings do not store their keys or a size, so there is no way to iterate them or query how many entries exist. Every possible key conceptually maps to a zero value. To enumerate entries, developers keep a separate array of keys.

Question 45Smart Contract Development with Solidity

A function is declared with the view modifier. What restriction does this impose?

  1. It may neither read nor modify state
  2. It may modify state only during the constructor
  3. It may read state but must not modify it Correct answer.
  4. It may modify state only if the caller sends no value

Explanation

A view function promises not to modify state; it can read state variables and call other view or pure functions. Writing to state, emitting events or creating contracts inside it would be rejected by the compiler. A pure function is stricter and cannot even read state.

Question 46Smart Contract Development with Solidity

Which declaration correctly defines a custom error in Solidity 0.8.x?

  1. event InsufficientBalance(uint256 available);
  2. error InsufficientBalance(uint256 available); Correct answer.
  3. require InsufficientBalance(uint256 available);
  4. exception InsufficientBalance(uint256 available);

Explanation

Custom errors are declared with the error keyword followed by a name and a parameter list, and are raised with revert. They are cheaper than revert strings because the ABI encodes a selector plus arguments instead of a string. Events, require and exception are not valid declaration forms for custom errors.

Question 47Smart Contract Development with Solidity

What is the effect of marking a function external rather than public?

  1. It cannot return any value
  2. It is callable only by the contract owner
  3. It can only be called from outside the contract Correct answer.
  4. It is callable only during construction

Explanation

External functions are part of the contract interface and are meant to be called from other contracts or transactions. They cannot be invoked internally by name without this.f(), which performs an actual external call. Public functions can be called both internally and externally.

Question 48Smart Contract Development with Solidity

Which Solidity type is best suited to store a fixed set of named choices such as Pending, Shipped and Delivered?

  1. mapping
  2. struct
  3. enum Correct answer.
  4. bytes32

Explanation

An enum defines a user-defined type restricted to a small set of named constants, which keeps values readable and range-checked. Values are stored as small unsigned integers. Structs group fields, bytes32 stores raw data and mappings store key-value pairs.

Question 49Smart Contract Development with Solidity

A contract stores uint256[] private balances;. Which approach lets external callers read individual entries without exposing the whole array?

  1. Write a function returning balances[index] Correct answer.
  2. Declare the array public so the compiler generates a getter
  3. Make the array constant so it becomes readable
  4. Emit the array in the constructor

Explanation

Private only restricts access from other contracts at the language level; a hand-written function can expose selected entries. Declaring the array public would generate a getter for every index, which is broader than intended. Constant arrays of dynamic size are not permitted.

Question 50Smart Contract Development with Solidity

A contract uses uint256[] public items;. How is the compiler-generated getter for this array invoked from another contract?

  1. items() returns the whole array
  2. items(uint256) returns one element Correct answer.
  3. items() returns the array length only
  4. getItems() returns the array length

Explanation

For public arrays the generated getter takes an index argument and returns the element at that position. It does not return the entire array or its length. Reading the length requires a separate function or direct access from inside the contract.