templates.atomicSwap

 1# Atomic Swaps - Example for illustrative purposes only.
 2
 3import smartpy as sp
 4
 5
 6@sp.module
 7def main():
 8    class AtomicSwap(sp.Contract):
 9        def __init__(self, notional, epoch, hashedSecret, owner, counterparty):
10            self.data.notional = notional
11            self.data.hashedSecret = hashedSecret
12            self.data.epoch = epoch
13            self.data.owner = owner
14            self.data.counterparty = counterparty
15
16        @sp.private(with_storage="read-write")
17        def checkAlive(self, identity):
18            assert self.data.notional != sp.mutez(0)
19            assert identity == sp.sender
20
21        @sp.private(with_storage="read-write")
22        def finish(self):
23            self.data.notional = sp.mutez(0)
24
25        @sp.entrypoint
26        def allSigned(self):
27            self.checkAlive(self.data.owner)
28            sp.send(self.data.counterparty, self.data.notional)
29            self.finish()
30
31        @sp.entrypoint
32        def cancelSwap(self):
33            self.checkAlive(self.data.owner)
34            assert self.data.epoch < sp.now
35            sp.send(self.data.owner, self.data.notional)
36            self.finish()
37
38        @sp.entrypoint
39        def knownSecret(self, params):
40            self.checkAlive(self.data.counterparty)
41            assert self.data.hashedSecret == sp.blake2b(params.secret)
42            sp.send(self.data.counterparty, self.data.notional)
43            self.finish()
44
45
46@sp.add_test()
47def test():
48    hashSecret = sp.blake2b(sp.bytes("0x12345678aabb"))
49    alice = sp.test_account("Alice")
50    bob = sp.test_account("Robert")
51    scenario = sp.test_scenario("AtomicSwap1", main)
52    c1 = main.AtomicSwap(
53        sp.mutez(12), sp.timestamp(50), hashSecret, alice.address, bob.address
54    )
55    scenario.h1("Atomic Swap")
56    scenario += c1
57
58
59@sp.add_test()
60def test():
61    alice = sp.test_account("Alice")
62    bob = sp.test_account("Robert")
63    scenario = sp.test_scenario("AtomicSwap2", main)
64    scenario.h1("Atomic Swap")
65
66    hashSecret = sp.blake2b(sp.bytes("0x12345678aabb"))
67    c1 = main.AtomicSwap(
68        sp.mutez(12), sp.timestamp(50), hashSecret, alice.address, bob.address
69    )
70    c2 = main.AtomicSwap(
71        sp.mutez(20), sp.timestamp(50), hashSecret, bob.address, alice.address
72    )
73    scenario.h1("c1")
74    c1.set_initial_balance(sp.tez(3))
75    scenario += c1
76    c1.knownSecret(secret=sp.bytes("0x12345678aa"), _sender=bob, _valid=False)
77    c1.knownSecret(secret=sp.bytes("0x12345678aabb"), _sender=bob)
78    scenario.h1("c2")
79    scenario += c2