Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

offer.gno

8.70 Kb · 300 lines
  1package rooms
  2
  3import (
  4	"chain"
  5	"chain/runtime/unsafe"
  6	"strconv"
  7	"strings"
  8
  9	"gno.land/p/nt/grc721/v0"
 10	"gno.land/r/nt/grc20reg/v0"
 11)
 12
 13// Offers: a room that completes in one transaction.
 14//
 15// The maker puts their side in as usual, then calls Offer with the exact
 16// list of what they want in return. That locks the maker's side on the new
 17// version. Whoever may take the other seat (the invited account, or anyone
 18// when the seat is open) calls Fill naming the version they reviewed and
 19// putting in exactly the wanted list: coins attached to the call, tokens
 20// and NFTs approved to this realm beforehand (the app sends the approvals
 21// and Fill in one transaction). Fill takes the seat, moves the wanted
 22// assets in and settles the room before it returns. Nothing partial: a
 23// wrong coin, a missing approval or a changed room fails the whole call.
 24//
 25// The maker can withdraw the offer at any time: Unlock, any deposit or
 26// withdrawal, or Cancel. Every change to the room clears it, and Fill names
 27// the version, so an offer can never be filled on terms the taker did not
 28// see. While an offer stands, Join is refused, so nobody can block an open
 29// offer by taking its seat without filling it.
 30
 31// Offer turns the room into an offer for exactly want, on the room as it is
 32// at version. want lists one asset per line, at most 8:
 33//
 34//	coin <amount> <denom>
 35//	token <amount> <grc20reg key>
 36//	nft 1 <collection key>#<token id>
 37//
 38// Amounts are in base units. Returns the new version, which the taker
 39// fills.
 40func Offer(cur realm, roomID uint64, version uint64, want string) uint64 {
 41	who := callerOf(cur)
 42	refuseCoins(cur)
 43	assertNotPaused()
 44
 45	r := mustRoom(roomID)
 46	r.assertLive()
 47	if who != r.maker.owner {
 48		panic("only the maker can make an offer")
 49	}
 50	if version != r.version {
 51		panic("the room changed: review version " + idString(r.version) + " and offer again")
 52	}
 53	if len(r.maker.assets) == 0 {
 54		panic("put something in before you make an offer")
 55	}
 56	if len(r.taker.assets) > 0 {
 57		panic("they have already put something in: agree in the room instead")
 58	}
 59	items := parseWant(want)
 60	for _, a := range items {
 61		r.assertAccepts(a.kind, a.denom)
 62	}
 63	r.assertStillVerified()
 64
 65	r.bump()
 66	r.want = items
 67	r.maker.locked = r.version
 68
 69	chain.Emit("Offered",
 70		"id", idString(r.id),
 71		"version", idString(r.version),
 72		"want", wantString(items),
 73	)
 74	return r.version
 75}
 76
 77// Fill completes an offer: the caller takes the other seat, puts in exactly
 78// what the offer wants, and the room settles in this call. version is the
 79// version the caller reviewed. Coins in the offer must be attached to this
 80// call, from the caller's own account.
 81func Fill(cur realm, roomID uint64, version uint64) {
 82	if !cur.IsCurrent() {
 83		panic("unauthorized: realm token is not current")
 84	}
 85	prev := cur.Previous()
 86	who := prev.Address()
 87	assertNotPaused()
 88
 89	r := mustRoom(roomID)
 90	r.assertLive()
 91	if len(r.want) == 0 {
 92		panic("this room has no standing offer")
 93	}
 94	if version != r.version {
 95		panic("the offer changed: review version " + idString(r.version) + " and fill again")
 96	}
 97	if r.maker.locked != r.version {
 98		panic("the offer is withdrawn")
 99	}
100	if who == r.maker.owner {
101		panic("you made this offer")
102	}
103	if r.taker.owner != "" && r.taker.owner != who {
104		panic("this offer is for another account")
105	}
106	if r.taker.owner == "" && !r.openSeat {
107		panic("this offer is for another account")
108	}
109	if len(r.taker.assets) > 0 {
110		panic("this room is not an offer any more")
111	}
112	r.assertStillVerified()
113
114	// Coins can only arrive with a direct call from the signing account,
115	// and they must be exactly the wanted coins: no more, no less, no other.
116	var sent chain.Coins
117	if prev.IsUserCall() {
118		sent = unsafe.OriginSend()
119	}
120	wantCoins := chain.Coins{}
121	for _, a := range r.want {
122		if a.kind == KindCoin {
123			wantCoins = append(wantCoins, chain.Coin{Denom: a.denom, Amount: a.amount})
124		}
125	}
126	if len(wantCoins) > 0 && !prev.IsUserCall() {
127		panic("send the coins with a direct call from your account")
128	}
129	if !sameCoins(sent, wantCoins) {
130		if len(wantCoins) == 0 {
131			panic("this offer does not take coins")
132		}
133		panic("attach exactly " + wantCoins.String())
134	}
135
136	// Say plainly what is missing before anything changes.
137	for _, a := range r.want {
138		switch a.kind {
139		case KindToken:
140			tok := grc20reg.Get(a.denom)
141			if tok == nil {
142				panic("token is not in the GRC20 registry")
143			}
144			if tok.BalanceOf(who) < a.amount {
145				panic("you do not have enough " + tok.GetSymbol())
146			}
147			if tok.Allowance(who, cur.Address()) < a.amount {
148				panic("approve this realm for " + tok.GetSymbol() + " first")
149			}
150		case KindNFT:
151			key, tid, _ := strings.Cut(a.denom, "#")
152			col := mustCollection(key)
153			if owner, err := col.token.OwnerOf(grc721.TokenID(tid)); err != nil || owner != who {
154				panic("you do not own " + col.token.GetName() + " #" + tid)
155			}
156			if to, err := col.token.GetApproved(grc721.TokenID(tid)); (err != nil || to != cur.Address()) && !col.token.IsApprovedForAll(who, cur.Address()) {
157				panic("approve this realm for " + col.token.GetName() + " #" + tid + " first")
158			}
159		}
160	}
161
162	// Hold the room while the wanted assets move in: an NFT's transfer runs
163	// its issuer's code, and nothing that code calls may change this room.
164	r.status = statusFilling
165	for _, a := range r.want {
166		switch a.kind {
167		case KindToken:
168			grc20reg.TransferFrom(0, cur, a.denom, who, cur.Address(), a.amount)
169		case KindNFT:
170			key, tid, _ := strings.Cut(a.denom, "#")
171			col := mustCollection(key)
172			if err := col.token.RealmTeller(0, cur).TransferFrom(0, cur, who, cur.Address(), grc721.TokenID(tid)); err != nil {
173				panic(err.Error())
174			}
175		}
176	}
177
178	// Everything is in custody: record the taker's side and swap.
179	r.status = StatusOpen
180	if r.taker.owner == "" {
181		r.taker.owner = who
182		index(who, r.id)
183	}
184	r.taker.assets = append([]asset{}, r.want...)
185	r.taker.locked = r.version
186	r.want = nil
187
188	chain.Emit("Filled",
189		"id", idString(r.id),
190		"taker", who.String(),
191		"version", idString(r.version),
192	)
193	r.settle(cur, who)
194}
195
196// parseWant reads an offer's want list; see Offer.
197func parseWant(want string) []asset {
198	items := []asset{}
199	for _, line := range strings.Split(want, "\n") {
200		line = strings.TrimSpace(line)
201		if line == "" {
202			continue
203		}
204		kind, rest, ok := strings.Cut(line, " ")
205		if !ok {
206			panic("each line of the want list is: kind amount denom")
207		}
208		amountText, denom, ok := strings.Cut(strings.TrimSpace(rest), " ")
209		denom = strings.TrimSpace(denom)
210		if !ok || denom == "" {
211			panic("each line of the want list is: kind amount denom")
212		}
213		amount, err := strconv.ParseInt(amountText, 10, 64)
214		if err != nil || amount <= 0 {
215			panic("want amounts must be positive whole numbers of base units")
216		}
217		switch kind {
218		case KindCoin:
219			assertDenom(denom)
220		case KindToken:
221			if grc20reg.Get(denom) == nil {
222				panic("token is not in the GRC20 registry: " + denom)
223			}
224		case KindNFT:
225			key, tid, ok := strings.Cut(denom, "#")
226			if !ok {
227				panic("an NFT is written as collection key#token id")
228			}
229			col := mustCollection(key)
230			assertTokenID(tid)
231			if _, err := col.token.OwnerOf(grc721.TokenID(tid)); err != nil {
232				panic("that NFT does not exist: " + denom)
233			}
234			if amount != 1 {
235				panic("an NFT is wanted whole: amount 1")
236			}
237		default:
238			panic("unknown kind in the want list: " + kind)
239		}
240		for _, a := range items {
241			if a.kind == kind && a.denom == denom {
242				panic("the want list names " + denom + " twice")
243			}
244		}
245		if len(items) >= MaxAssetsPerSide {
246			panic("an offer can want at most 8 different assets")
247		}
248		items = append(items, asset{kind: kind, denom: denom, amount: amount})
249	}
250	if len(items) == 0 {
251		panic("say what you want in return")
252	}
253	return items
254}
255
256// wantString writes a want list back in Offer's format.
257func wantString(items []asset) string {
258	lines := make([]string, 0, len(items))
259	for _, a := range items {
260		lines = append(lines, a.kind+" "+strconv.FormatInt(a.amount, 10)+" "+a.denom)
261	}
262	return strings.Join(lines, "\n")
263}
264
265// assertDenom accepts bank denoms: 3 to 128 characters of lowercase
266// letters, digits and / : . _ -, starting with a letter.
267func assertDenom(d string) {
268	if len(d) < 3 || len(d) > 128 {
269		panic("not a coin denom: " + d)
270	}
271	for i, c := range d {
272		ok := c >= 'a' && c <= 'z' || i > 0 && (c >= '0' && c <= '9' || c == '/' || c == ':' || c == '.' || c == '_' || c == '-')
273		if !ok {
274			panic("not a coin denom: " + d)
275		}
276	}
277}
278
279// sameCoins reports whether a and b hold the same amount of every denom.
280func sameCoins(a, b chain.Coins) bool {
281	total := func(cs chain.Coins) map[string]int64 {
282		m := map[string]int64{}
283		for _, c := range cs {
284			if c.Amount != 0 {
285				m[c.Denom] += c.Amount
286			}
287		}
288		return m
289	}
290	ma, mb := total(a), total(b)
291	if len(ma) != len(mb) {
292		return false
293	}
294	for d, n := range ma {
295		if mb[d] != n {
296			return false
297		}
298	}
299	return true
300}