SMART CONTRACTS, DEFI & WEB3 SECURITY - Chapter 1, Exercise 1 Solution ========================================================== Designing a decrement() Function PROBLEM ------- Using this chapter's own Counter contract as a model, describe (in plain English, no code required) what a decrement() function would need to do, and whether it should be marked view, pure, or neither. Justify your answer. SOLUTION -------- A decrement() function needs to reduce the contract's own count state variable by one - mirroring exactly what increment() does, just in the opposite direction. Since count is a state variable, actually changing its stored value means this function is modifying the contract's own permanent on-chain state. It should be marked neither view nor pure. This chapter's own definitions are precise about what each modifier promises: - view promises the function will READ state but never MODIFY it. - pure promises the function won't even read state at all. decrement() does the opposite of both of these - it actively writes a new value to a state variable. Marking it view or pure would be a false promise the compiler would actually reject, since Solidity checks that a function's real behavior matches whichever modifier (if any) it claims. A function like this, with no modifier at all, is understood to freely read and write state as needed - exactly the category increment() itself already falls into in this chapter's own example. A realistic, complete version might also need one extra real-world consideration this chapter didn't require for increment(): deciding what should happen if count is already 0 and someone calls decrement() - should it be allowed to go negative (not possible for an unsigned uint type at all), stay at 0, or should the call fail outright? That specific design decision goes beyond what this chapter covered, but recognizing the question is worth noting. ANSWER: decrement() should have neither the view nor pure modifier, since it needs to write a new value to the count state variable - the exact opposite of what both of those modifiers promise not to do. ---- WHY THIS WORKS AS AN ANSWER This correctly applies the chapter's own precise view/pure definitions to a new function by identifying that state is being modified, not just read or ignored, and explains why the compiler itself would reject a mismatched modifier rather than just asserting the correct answer.