Show contents
Chapter 5 of 6 · 25 min
Project: a solidarity crowdfunding contract
By the end of this chapter, you'll be able to
- Translate crowdfunding rules into a contract with clear states
- Use the block number as a deterministic clock
- Prefer "on demand" refunds to payments in a loop
- Test the contract with success, failure and abuse scenarios
The contract's rules
At the end, nothing remains locked in the contract.
Text description of the animation
- Everyone sends funds as long as the deadline block has not been reached; the contract records each contribution.
- The block number serves as the clock: every node sees the same value, unlike local time.
- If the total reaches the goal, only the beneficiary can withdraw, and only once.
- Otherwise, each donor comes to collect their own contribution: no loop over every donor.
- At the end, nothing remains locked in the contract.
The contract has four functions. Two design rules guide everything else:
- the clock is the block number, not the computer's time (which would differ from one node to another);
- each donor comes to collect their refund (the pull pattern), instead of the contract paying everyone in a loop (the push pattern), for the reason explained in the pitfall.
class Fund:
def __init__(self, beneficiary, goal, deadline_block):
self.beneficiary, self.goal, self.deadline_block = beneficiary, goal, deadline_block
self.contributions, self.total, self.claimed = {}, 0, False
def contribute(self, ch, who, amount):
if ch.block >= self.deadline_block:
raise ValueError("collection closed")
if amount <= 0:
raise ValueError("invalid amount")
ch.transfer(who, "fund", amount)
self.contributions[who] = self.contributions.get(who, 0) + amount
self.total += amount
class Chain:
def __init__(self, balances):
self.balances, self.block = dict(balances), 100
def transfer(self, sender, recipient, amount):
if self.balances.get(sender, 0) < amount:
raise ValueError(f"insufficient balance for {sender}")
self.balances[sender] -= amount
self.balances[recipient] = self.balances.get(recipient, 0) + amount
ch = Chain({"Awa": 900_000, "Kofi": 400_000, "Mei": 800_000, "fund": 0})
f = Fund("treasurer", goal=2_000_000, deadline_block=200)
for who, amount in [("Awa", 600_000), ("Kofi", 300_000), ("Mei", 700_000)]:
f.contribute(ch, who, amount)
print("total:", f.total, "| contributions:", f.contributions)
ch.block = 200
try:
f.contribute(ch, "Awa", 100_000)
except ValueError as e:
print("after the deadline:", e)
total: 1600000 | contributions: {'Awa': 600000, 'Kofi': 300000, 'Mei': 700000}
after the deadline: collection closed
Mini-lab: imagine the abusesPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Project: the complete fund
Complete the Fund class with:
claim(ch, who): only after the deadline block, only if the goal is reached, only by the beneficiary, only once;refund(ch, who): only after the deadline block, only if the goal is not reached, only for a donor, only once (checks, effects, then transfer).
Test two funds: one that succeeds (with an early withdrawal attempt, an attempt by someone else and a double withdrawal), and one that fails (with a double refund and a request from someone who gave nothing). Check that at the end each contract's balance is zero.
Hint 1
if ...: raise ValueError("..."), one per rule. The order of the checks determines the error message displayed.Hint 2
refund, read the amount, set self.contributions[who] = 0, then transfer: a second call will find 0 and be refused.Show the solution and common mistakes
class Chain:
def __init__(self, balances):
self.balances, self.block = dict(balances), 100
def transfer(self, sender, recipient, amount):
if self.balances.get(sender, 0) < amount:
raise ValueError(f"insufficient balance for {sender}")
self.balances[sender] -= amount
self.balances[recipient] = self.balances.get(recipient, 0) + amount
def call(self, contract, function, *args):
try:
getattr(contract, function)(self, *args)
return "ok"
except ValueError as e:
return f"refused: {e}"
class Fund:
def __init__(self, name, beneficiary, goal, deadline_block):
self.name, self.beneficiary, self.goal, self.deadline_block = name, beneficiary, goal, deadline_block
self.contributions, self.total, self.claimed = {}, 0, False
def contribute(self, ch, who, amount):
if ch.block >= self.deadline_block: raise ValueError("collection closed")
if amount <= 0: raise ValueError("invalid amount")
ch.transfer(who, self.name, amount)
self.contributions[who] = self.contributions.get(who, 0) + amount
self.total += amount
def claim(self, ch, who):
if ch.block < self.deadline_block: raise ValueError("collection ongoing")
if self.total < self.goal: raise ValueError("goal not reached")
if who != self.beneficiary: raise ValueError("reserved for the beneficiary")
if self.claimed: raise ValueError("already claimed")
self.claimed = True # effect before interaction
ch.transfer(self.name, who, self.total)
def refund(self, ch, who):
if ch.block < self.deadline_block: raise ValueError("collection ongoing")
if self.total >= self.goal: raise ValueError("goal reached: no refund")
amount = self.contributions.get(who, 0)
if amount == 0: raise ValueError("nothing to refund")
self.contributions[who] = 0 # effect before interaction
ch.transfer(self.name, who, amount)
ch = Chain({"Awa": 900_000, "Kofi": 900_000, "Mei": 900_000, "Yao": 50_000, "roof": 0, "well": 0})
roof = Fund("roof", "treasurer", 2_000_000, deadline_block=200)
well = Fund("well", "treasurer", 1_000_000, deadline_block=200)
for who, a in [("Awa", 800_000), ("Kofi", 700_000), ("Mei", 600_000)]:
ch.call(roof, "contribute", who, a)
for who, a in [("Awa", 50_000), ("Kofi", 100_000)]:
ch.call(well, "contribute", who, a)
print("1.", ch.call(roof, "claim", "treasurer")) # too early
ch.block = 200
print("2.", ch.call(roof, "claim", "Yao")) # not the beneficiary
print("3.", ch.call(roof, "claim", "treasurer"))
print("4.", ch.call(roof, "claim", "treasurer")) # double withdrawal
print("5.", ch.call(roof, "refund", "Awa")) # goal reached
print("6.", ch.call(well, "refund", "Awa"))
print("7.", ch.call(well, "refund", "Awa")) # double refund
print("8.", ch.call(well, "refund", "Yao")) # gave nothing
print("9.", ch.call(well, "refund", "Kofi"))
print("contract balances:", ch.balances["roof"], ch.balances["well"], "| treasurer:", ch.balances["treasurer"])
1. refused: collection ongoing
2. refused: reserved for the beneficiary
3. ok
4. refused: already claimed
5. refused: goal reached: no refund
6. ok
7. refused: nothing to refund
8. refused: nothing to refund
9. ok
contract balances: 0 0 | treasurer: 2100000
Each abuse is refused with a precise message, and at the end both contracts are empty: 2,100,000 F CFA for the roof, and the well's donors got everything back. Notice that the roof collection exceeded the goal: the contract pays out the whole total, as announced; another rule (refunding the surplus, capping) would have to be written and tested explicitly.
Common mistakes:
- Using the computer's time (
time.time()) instead of the block number: each node would get a different result. - Comparing with
>instead of>=for the goal or the deadline: a fund that reaches exactly its goal would be considered failed. - Forgetting that a deployed contract cannot be fixed: a missing rule (for example a deadline that is too far away) locks the funds with no recourse.
Summary
- 1A contract translates rules into states and conditions: each function first checks everything that must be true.
- 2The block number serves as a deterministic clock, identical for every node.
- 3Refunds are made on demand (pull), never in a loop that can fail or exceed the gas limit.
- 4Abuse scenarios are tested as much as the normal scenario, because a deployed contract is not easily fixed.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.