atomicswap.gno
5.41 Kb ยท 175 lines
1// Package atomicswap implements a hash time-locked contract (HTLC) for atomic swaps
2// between native coins (ugnot) or GRC20 tokens.
3//
4// An atomic swap allows two parties to exchange assets in a trustless way, where
5// either both transfers happen or neither does. The process works as follows:
6//
7// 1. Alice wants to swap with Bob. She generates a secret and creates a swap with
8// Bob's address and the hash of the secret (hashlock).
9//
10// 2. Bob can claim the assets by providing the correct secret before the timelock expires.
11// The secret proves Bob knows the preimage of the hashlock.
12//
13// 3. If Bob doesn't claim in time, Alice can refund the assets back to herself.
14//
15// Example usage for native coins:
16//
17// // Alice creates a swap with 1000ugnot for Bob
18// secret := "mysecret"
19// hashlock := hex.EncodeToString(sha256.Sum256([]byte(secret)))
20// id, _ := atomicswap.NewCoinSwap(bobAddr, hashlock) // -send 1000ugnot
21//
22// // Bob claims the swap by providing the secret
23// atomicswap.Claim(id, "mysecret")
24//
25// Example usage for GRC20 tokens:
26//
27// // Alice approves the swap contract to spend her tokens
28// token.Approve(swapAddr, 1000)
29//
30// // Alice creates a swap with 1000 tokens for Bob
31// id, _ := atomicswap.NewGRC20Swap(bobAddr, hashlock, "gno.land/r/demo/token")
32//
33// // Bob claims the swap by providing the secret
34// atomicswap.Claim(id, "mysecret")
35//
36// If Bob doesn't claim in time (default 1 week), Alice can refund:
37//
38// atomicswap.Refund(id)
39package atomicswap
40
41import (
42 "std"
43 "strconv"
44 "time"
45
46 "gno.land/p/demo/avl"
47 "gno.land/p/demo/grc/grc20"
48 "gno.land/p/demo/ufmt"
49 "gno.land/r/demo/grc20reg"
50)
51
52const defaultTimelockDuration = 7 * 24 * time.Hour // 1w
53
54var (
55 swaps avl.Tree // id -> *Swap
56 counter int
57)
58
59// NewCoinSwap creates a new atomic swap contract for native coins.
60// It uses a default timelock duration.
61func NewCoinSwap(recipient std.Address, hashlock string) (int, *Swap) {
62 timelock := time.Now().Add(defaultTimelockDuration)
63 return NewCustomCoinSwap(recipient, hashlock, timelock)
64}
65
66// NewGRC20Swap creates a new atomic swap contract for grc20 tokens.
67// It uses gno.land/r/demo/grc20reg to lookup for a registered token.
68func NewGRC20Swap(recipient std.Address, hashlock string, tokenRegistryKey string) (int, *Swap) {
69 timelock := time.Now().Add(defaultTimelockDuration)
70 tokenGetter := grc20reg.MustGet(tokenRegistryKey)
71 token := tokenGetter()
72 return NewCustomGRC20Swap(recipient, hashlock, timelock, token)
73}
74
75// NewCoinSwapWithTimelock creates a new atomic swap contract for native coin.
76// It allows specifying a custom timelock duration.
77// It is not callable with `gnokey maketx call`, but can be imported by another contract or `gnokey maketx run`.
78func NewCustomCoinSwap(recipient std.Address, hashlock string, timelock time.Time) (int, *Swap) {
79 sender := std.PreviousRealm().Address()
80 sent := std.OriginSend()
81 require(len(sent) != 0, "at least one coin needs to be sent")
82
83 // Create the swap
84 sendFn := func(to std.Address) {
85 banker := std.NewBanker(std.BankerTypeRealmSend)
86 pkgAddr := std.CurrentRealm().Address()
87 banker.SendCoins(pkgAddr, to, sent)
88 }
89 amountStr := sent.String()
90 swap := newSwap(sender, recipient, hashlock, timelock, amountStr, sendFn)
91
92 counter++
93 id := strconv.Itoa(counter)
94 swaps.Set(id, swap)
95 return counter, swap
96}
97
98// NewCustomGRC20Swap creates a new atomic swap contract for grc20 tokens.
99// It is not callable with `gnokey maketx call`, but can be imported by another contract or `gnokey maketx run`.
100func NewCustomGRC20Swap(recipient std.Address, hashlock string, timelock time.Time, token *grc20.Token) (int, *Swap) {
101 sender := std.PreviousRealm().Address()
102 curAddr := std.CurrentRealm().Address()
103
104 allowance := token.Allowance(sender, curAddr)
105 require(allowance > 0, "no allowance")
106
107 userTeller := token.CallerTeller()
108 err := userTeller.TransferFrom(sender, curAddr, allowance)
109 require(err == nil, "cannot retrieve tokens from allowance")
110
111 amountStr := ufmt.Sprintf("%d%s", allowance, token.GetSymbol())
112 sendFn := func(to std.Address) {
113 err := userTeller.Transfer(to, allowance)
114 require(err == nil, "cannot transfer tokens")
115 }
116
117 swap := newSwap(sender, recipient, hashlock, timelock, amountStr, sendFn)
118
119 counter++
120 id := strconv.Itoa(counter)
121 swaps.Set(id, swap)
122
123 return counter, swap
124}
125
126// Claim loads a registered swap and tries to claim it.
127func Claim(id int, secret string) {
128 swap := mustGet(id)
129 swap.Claim(secret)
130}
131
132// Refund loads a registered swap and tries to refund it.
133func Refund(id int) {
134 swap := mustGet(id)
135 swap.Refund()
136}
137
138// Render returns a list of swaps (simplified) for the homepage, and swap details when specifying a swap ID.
139func Render(path string) string {
140 if path == "" { // home
141 output := ""
142 size := swaps.Size()
143 max := 10
144 swaps.ReverseIterateByOffset(size-max, max, func(key string, value any) bool {
145 swap := value.(*Swap)
146 output += ufmt.Sprintf("- %s: %s -(%s)> %s - %s\n",
147 key, swap.sender, swap.amountStr, swap.recipient, swap.Status())
148 return false
149 })
150 return output
151 } else { // by id
152 swap, ok := swaps.Get(path)
153 if !ok {
154 return "404"
155 }
156 return swap.(*Swap).String()
157 }
158}
159
160// require checks a condition and panics with a message if the condition is false.
161func require(check bool, msg string) {
162 if !check {
163 panic(msg)
164 }
165}
166
167// mustGet retrieves a swap by its id or panics.
168func mustGet(id int) *Swap {
169 key := strconv.Itoa(id)
170 swap, ok := swaps.Get(key)
171 if !ok {
172 panic("unknown swap ID")
173 }
174 return swap.(*Swap)
175}