BC7: Writing smart contracts in Solidity

Lesson 4 of 5 ยท reading 15โ€“25 minutes; practice and project time is on the module page

Handling ether safely

๐ŸŽฏYou'll be able to

Receive and send ether in a contract without losing it or trusting it to arrive.

๐Ÿ The everyday picture

A cashier who writes the receipt before handing over cash, checks the customer actually took it, and won't accept money pushed under the window without a form.

๐Ÿ“˜What it really is

๐Ÿ“A worked example

Input: a member withdraws 0.2 test ether.

Steps:

  1. Checks: the amount is more than zero, within the limit, and not more than their balance.
  2. Effects: reduce their balance and the total.
  3. Interaction: send with call, and revert if it fails, which also undoes step 2.

Expected output: the member gets 0.2, or nothing changes at all.

๐ŸŒWhere it's used

๐Ÿ“Case scenario

A contract sent ether with call and didn't check the result. One member's address was a contract that refused payments; its balance was reduced to zero but no ether arrived, and the record no longer matched the contract's holdings. Checking ok and reverting kept the record right.

๐Ÿ–ฑ๏ธTry it

Rewrite the starter's withdraw steps in the order checks, effects, interactions, without writing code yet. Success: the balance update comes before the call, and the call's result is checked.

โš ๏ธCommon mistakes

๐Ÿ› ๏ธFor your project

Project 1's tests 5, 8 and 9 check failed payments, plain transfers, and that the contract's ether matches its records.

โœ…Quick check

What order should a function follow when sending ether?

Show the answer

Checks, then effects (update records), then interactions (send).

Why revert in receive() for SakhiFund?

Show the answer

Plain ether wouldn't be credited to anyone and would be stuck.

โ† PreviousWho may do what: modifiers, errors and events
ProLearners Assist