atomicswap.gno

5.48 Kb ยท 174 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(cur realm, recipient std.Address, hashlock string) (int, *Swap) {
 62	timelock := time.Now().Add(defaultTimelockDuration)
 63	return NewCustomCoinSwap(cur, 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(cur realm, recipient std.Address, hashlock string, tokenRegistryKey string) (int, *Swap) {
 69	timelock := time.Now().Add(defaultTimelockDuration)
 70	token := grc20reg.MustGet(tokenRegistryKey)
 71	return NewCustomGRC20Swap(cur, recipient, hashlock, timelock, token)
 72}
 73
 74// NewCoinSwapWithTimelock creates a new atomic swap contract for native coin.
 75// It allows specifying a custom timelock duration.
 76// It is not callable with `gnokey maketx call`, but can be imported by another contract or `gnokey maketx run`.
 77func NewCustomCoinSwap(cur realm, recipient std.Address, hashlock string, timelock time.Time) (int, *Swap) {
 78	sender := std.PreviousRealm().Address()
 79	sent := std.OriginSend()
 80	require(len(sent) != 0, "at least one coin needs to be sent")
 81
 82	// Create the swap
 83	sendFn := func(cur realm, to std.Address) {
 84		banker := std.NewBanker(std.BankerTypeRealmSend)
 85		pkgAddr := std.CurrentRealm().Address()
 86		banker.SendCoins(pkgAddr, to, sent)
 87	}
 88	amountStr := sent.String()
 89	swap := newSwap(sender, recipient, hashlock, timelock, amountStr, sendFn)
 90
 91	counter++
 92	id := strconv.Itoa(counter)
 93	swaps.Set(id, swap)
 94	return counter, swap
 95}
 96
 97// NewCustomGRC20Swap creates a new atomic swap contract for grc20 tokens.
 98// It is not callable with `gnokey maketx call`, but can be imported by another contract or `gnokey maketx run`.
 99func NewCustomGRC20Swap(cur realm, recipient std.Address, hashlock string, timelock time.Time, token *grc20.Token) (int, *Swap) {
100	sender := std.PreviousRealm().Address()
101	curAddr := std.CurrentRealm().Address()
102
103	allowance := token.Allowance(sender, curAddr)
104	require(allowance > 0, "no allowance")
105
106	userTeller := token.RealmTeller()
107	err := userTeller.TransferFrom(sender, curAddr, allowance)
108	require(err == nil, "cannot retrieve tokens from allowance")
109
110	amountStr := ufmt.Sprintf("%d%s", allowance, token.GetSymbol())
111	sendFn := func(cur realm, to std.Address) {
112		err := userTeller.Transfer(to, allowance)
113		require(err == nil, "cannot transfer tokens")
114	}
115
116	swap := newSwap(sender, recipient, hashlock, timelock, amountStr, sendFn)
117
118	counter++
119	id := strconv.Itoa(counter)
120	swaps.Set(id, swap)
121
122	return counter, swap
123}
124
125// Claim loads a registered swap and tries to claim it.
126func Claim(cur realm, id int, secret string) {
127	swap := mustGet(id)
128	swap.Claim(secret)
129}
130
131// Refund loads a registered swap and tries to refund it.
132func Refund(cur realm, id int) {
133	swap := mustGet(id)
134	swap.Refund()
135}
136
137// Render returns a list of swaps (simplified) for the homepage, and swap details when specifying a swap ID.
138func Render(path string) string {
139	if path == "" { // home
140		output := ""
141		size := swaps.Size()
142		max := 10
143		swaps.ReverseIterateByOffset(size-max, max, func(key string, value any) bool {
144			swap := value.(*Swap)
145			output += ufmt.Sprintf("- %s: %s -(%s)> %s - %s\n",
146				key, swap.sender, swap.amountStr, swap.recipient, swap.Status())
147			return false
148		})
149		return output
150	} else { // by id
151		swap, ok := swaps.Get(path)
152		if !ok {
153			return "404"
154		}
155		return swap.(*Swap).String()
156	}
157}
158
159// require checks a condition and panics with a message if the condition is false.
160func require(check bool, msg string) {
161	if !check {
162		panic(msg)
163	}
164}
165
166// mustGet retrieves a swap by its id or panics.
167func mustGet(id int) *Swap {
168	key := strconv.Itoa(id)
169	swap, ok := swaps.Get(key)
170	if !ok {
171		panic("unknown swap ID")
172	}
173	return swap.(*Swap)
174}