templates.escrow

 1# Escrow - Example for illustrative purposes only.
 2
 3import smartpy as sp
 4
 5
 6@sp.module
 7def main():
 8    class Escrow(sp.Contract):
 9        def __init__(
10            self, owner, fromOwner, counterparty, fromCounterparty, epoch, hashedSecret
11        ):
12            self.data.fromOwner = fromOwner
13            self.data.fromCounterparty = fromCounterparty
14            self.data.balanceOwner = sp.tez(0)
15            self.data.balanceCounterparty = sp.tez(0)
16            self.data.hashedSecret = hashedSecret
17            self.data.epoch = epoch
18            self.data.owner = owner
19            self.data.counterparty = counterparty
20
21        @sp.entrypoint
22        def addBalanceOwner(self):
23            assert self.data.balanceOwner == sp.tez(0)
24            assert sp.amount == self.data.fromOwner
25            self.data.balanceOwner = self.data.fromOwner
26
27        @sp.entrypoint
28        def addBalanceCounterparty(self):
29            assert self.data.balanceCounterparty == sp.tez(0)
30            assert sp.amount == self.data.fromCounterparty
31            self.data.balanceCounterparty = self.data.fromCounterparty
32
33        @sp.private(with_storage="read-write", with_operations=True)
34        def claim(self, identity):
35            assert sp.sender == identity
36            sp.send(identity, self.data.balanceOwner + self.data.balanceCounterparty)
37            self.data.balanceOwner = sp.tez(0)
38            self.data.balanceCounterparty = sp.tez(0)
39
40        @sp.entrypoint
41        def claimCounterparty(self, params):
42            assert sp.now < self.data.epoch
43            assert self.data.hashedSecret == sp.blake2b(params.secret)
44            self.claim(self.data.counterparty)
45
46        @sp.entrypoint
47        def claimOwner(self):
48            assert self.data.epoch < sp.now
49            self.claim(self.data.owner)
50
51
52@sp.add_test()
53def test():
54    scenario = sp.test_scenario("Escrow", main)
55    scenario.h1("Escrow")
56    hashSecret = sp.blake2b(sp.bytes("0x01223344"))
57    alice = sp.test_account("Alice")
58    bob = sp.test_account("Bob")
59    c1 = main.Escrow(
60        alice.address, sp.tez(50), bob.address, sp.tez(4), sp.timestamp(123), hashSecret
61    )
62    scenario += c1
63    c1.addBalanceOwner(_sender=alice, _amount=sp.tez(50))
64    c1.addBalanceCounterparty(_sender=bob, _amount=sp.tez(4))
65    scenario.h3("Erronous secret")
66    c1.claimCounterparty(secret=sp.bytes("0x01223343"), _sender=bob, _valid=False)
67    scenario.h3("Correct secret")
68    c1.claimCounterparty(secret=sp.bytes("0x01223344"), _sender=bob)