escrow.gno
10.37 Kb · 332 lines
1package cust0dy
2
3import (
4 "crypto/sha256"
5 "encoding/hex"
6 "strconv"
7 "time"
8
9 "chain"
10 "chain/banker"
11 "chain/runtime/unsafe"
12
13 core "gno.land/p/g1ejwp09wwnu6psem2sdwrh7l7xcldqm6zz3vu2v/cust0dy_core"
14)
15
16func bankerNew(cur realm) banker.Banker {
17 return banker.NewBanker(banker.BankerTypeRealmSend, cur)
18}
19
20func require(cond bool, msg string) {
21 if !cond {
22 panic(msg)
23 }
24}
25
26// ---- roles ----
27
28// ClaimAdmin makes the caller the marketplace operator, once. The deployer
29// calls this right after deployment; afterwards it panics for everyone.
30// The first admin also becomes the first arbiter.
31func ClaimAdmin(cur realm) {
32 mustUserCall(cur)
33 if admin != address("") {
34 panic("admin already claimed")
35 }
36 admin = cur.Previous().Address()
37 arbiter = admin
38 chain.Emit("AdminClaimed", "admin", admin.String())
39}
40
41// SetArbiter changes the dispute referee. Admin only.
42func SetArbiter(cur realm, a address) {
43 mustAdmin(cur)
44 require(a != address(""), "empty arbiter")
45 arbiter = a
46 chain.Emit("ArbiterChanged", "arbiter", a.String())
47}
48
49// WithdrawFees sends accrued platform fees to the admin. Admin only.
50func WithdrawFees(cur realm) {
51 mustAdmin(cur)
52 require(feesUgnot > 0, "no fees to withdraw")
53 amt := feesUgnot
54 feesUgnot = 0
55 send(cur, admin, amt)
56 chain.Emit("FeesWithdrawn", "amount", strconv.FormatInt(amt, 10))
57}
58
59// ---- sell side ----
60
61// List creates a sell order for a domain, social handle or Gno handle.
62// The asset is not verified yet; see VerificationCode and AttestVerified.
63func List(cur realm, kindStr, value string, priceUgnot int64) int {
64 mustUserCall(cur)
65 kind, err := core.ParseKind(kindStr)
66 if err != nil {
67 panic(err.Error())
68 }
69 require(core.ValidateAsset(kind, value) == nil, "invalid asset for its kind")
70 require(priceUgnot > 0, "price must be positive")
71 require(priceUgnot <= core.MaxPrice, "price too large")
72
73 listingSeq++
74 l := &Listing{
75 ID: listingSeq,
76 Seller: cur.Previous().Address(),
77 Kind: kind,
78 Value: value,
79 PriceUgnot: priceUgnot,
80 State: core.ListingOpen,
81 Created: time.Now(),
82 }
83 listings.Set(strconv.Itoa(l.ID), l)
84 chain.Emit("ListingCreated",
85 "id", strconv.Itoa(l.ID),
86 "seller", l.Seller.String(),
87 "kind", kind.String(),
88 "value", value,
89 "price", strconv.FormatInt(priceUgnot, 10),
90 )
91 return l.ID
92}
93
94// VerificationCode is the string the seller must publish off-chain to prove
95// control of the asset: a DNS TXT record for a domain, a bio/post code for
96// a social or Gno handle. It binds the listing id and the seller address,
97// so a code cannot be reused for someone else's listing.
98func VerificationCode(id int) string {
99 l := getListing(id)
100 sum := sha256.Sum256([]byte("cust0dy:" + l.Seller.String() + ":" + strconv.Itoa(id)))
101 return "c0_" + hex.EncodeToString(sum[:])[:12]
102}
103
104// AttestVerified marks a listing as ownership-verified. Only the arbiter
105// (or admin) may attest, and only after an off-chain check, for example
106// with verifier/dns_verify.py. The attestation is public and on the record.
107func AttestVerified(cur realm, id int) {
108 mustArbiter(cur)
109 l := getListing(id)
110 require(l.State == core.ListingOpen, "listing not open")
111 require(!l.Verified, "already verified")
112 l.Verified = true
113 chain.Emit("ListingVerified", "id", strconv.Itoa(id), "arbiter", cur.Previous().Address().String())
114}
115
116// CancelListing withdraws an open listing. Seller only, and only while no
117// live escrow holds it.
118func CancelListing(cur realm, id int) {
119 mustUserCall(cur)
120 l := getListing(id)
121 require(l.Seller == cur.Previous().Address(), "not your listing")
122 require(l.State == core.ListingOpen, "listing not open")
123 l.State = core.ListingCancelled
124 chain.Emit("ListingCancelled", "id", strconv.Itoa(id))
125}
126
127// ---- buy side ----
128
129// Buy purchases a listing at full price. The buyer must attach exactly
130// BuyerTotal(price) ugnot (price + 2.5% buyer fee). The coins lock in this
131// realm until settlement. Returns the escrow id.
132func Buy(cur realm, listingID int) int {
133 mustUserCall(cur)
134 l := getListing(listingID)
135 require(l.State == core.ListingOpen, "listing not open")
136 buyer := cur.Previous().Address()
137 require(buyer != l.Seller, "cannot buy your own listing")
138
139 want := core.BuyerTotal(l.PriceUgnot)
140 sent := unsafe.OriginSend()
141 require(len(sent) == 1 && sent[0].Denom == "ugnot" && sent[0].Amount == want,
142 "attach exactly "+strconv.FormatInt(want, 10)+"ugnot (price + 2.5% buyer fee)")
143
144 l.State = core.ListingSold
145 escrowSeq++
146 e := &Escrow{
147 ID: escrowSeq,
148 ListingID: l.ID,
149 Seller: l.Seller,
150 Buyer: buyer,
151 PriceUgnot: l.PriceUgnot,
152 LockedUgnot: want,
153 State: core.StateFunded,
154 FundedAt: time.Now(),
155 }
156 escrows.Set(strconv.Itoa(e.ID), e)
157 chain.Emit("EscrowFunded",
158 "id", strconv.Itoa(e.ID),
159 "listing", strconv.Itoa(l.ID),
160 "buyer", buyer.String(),
161 "locked", strconv.FormatInt(want, 10),
162 )
163 return e.ID
164}
165
166// MakeOffer locks coins as a buy-side offer on a listing. Offers are
167// all-in: no extra buyer fee is charged if the seller accepts. Attach the
168// offered amount as ugnot. Returns the offer id.
169func MakeOffer(cur realm, listingID int) int {
170 mustUserCall(cur)
171 l := getListing(listingID)
172 require(l.State == core.ListingOpen, "listing not open")
173 maker := cur.Previous().Address()
174 require(maker != l.Seller, "cannot offer on your own listing")
175
176 sent := unsafe.OriginSend()
177 require(len(sent) == 1 && sent[0].Denom == "ugnot" && sent[0].Amount > 0,
178 "attach the offered amount in ugnot")
179
180 offerSeq++
181 o := &Offer{
182 ID: offerSeq,
183 ListingID: l.ID,
184 Maker: maker,
185 AmountUgnot: sent[0].Amount,
186 Open: true,
187 Created: time.Now(),
188 }
189 offers.Set(strconv.Itoa(o.ID), o)
190 chain.Emit("OfferMade",
191 "id", strconv.Itoa(o.ID),
192 "listing", strconv.Itoa(l.ID),
193 "maker", maker.String(),
194 "amount", strconv.FormatInt(o.AmountUgnot, 10),
195 )
196 return o.ID
197}
198
199// CancelOffer withdraws an open offer and refunds the maker in full.
200func CancelOffer(cur realm, offerID int) {
201 mustUserCall(cur)
202 o := getOffer(offerID)
203 require(o.Open, "offer not open")
204 require(o.Maker == cur.Previous().Address(), "not your offer")
205 o.Open = false
206 send(cur, o.Maker, o.AmountUgnot)
207 chain.Emit("OfferCancelled", "id", strconv.Itoa(offerID))
208}
209
210// AcceptOffer lets the seller accept an open offer. The offer's locked
211// coins become the escrow; the buyer fee is waived (offers are all-in) and
212// only the 5% seller fee applies at settlement. Returns the escrow id.
213func AcceptOffer(cur realm, offerID int) int {
214 mustUserCall(cur)
215 o := getOffer(offerID)
216 require(o.Open, "offer not open")
217 l := getListing(o.ListingID)
218 require(l.Seller == cur.Previous().Address(), "not your listing")
219 require(l.State == core.ListingOpen, "listing not open")
220
221 o.Open = false
222 l.State = core.ListingSold
223 escrowSeq++
224 e := &Escrow{
225 ID: escrowSeq,
226 ListingID: l.ID,
227 Seller: l.Seller,
228 Buyer: o.Maker,
229 PriceUgnot: o.AmountUgnot,
230 LockedUgnot: o.AmountUgnot,
231 State: core.StateFunded,
232 FundedAt: time.Now(),
233 }
234 escrows.Set(strconv.Itoa(e.ID), e)
235 chain.Emit("OfferAccepted",
236 "offer", strconv.Itoa(o.ID),
237 "escrow", strconv.Itoa(e.ID),
238 "listing", strconv.Itoa(l.ID),
239 )
240 return e.ID
241}
242
243// ---- escrow transitions ----
244
245// MarkTransferSubmitted records that the seller has started the off-chain
246// handover (registrar push, credential handover, ...). This stops the
247// buyer's automatic refund window; from here the exits are buyer
248// confirmation or a dispute.
249func MarkTransferSubmitted(cur realm, escrowID int) {
250 mustUserCall(cur)
251 e := getEscrow(escrowID)
252 require(e.Seller == cur.Previous().Address(), "seller only")
253 require(e.State == core.StateFunded, "not in funded state")
254 e.State = core.StateTransferSubmitted
255 chain.Emit("TransferSubmitted", "id", strconv.Itoa(escrowID))
256}
257
258// ConfirmReceived settles the trade: the seller is paid the agreed price
259// minus the 5% seller fee; the remainder of the locked coins is platform
260// fee. Buyer only. Never confirm before the asset is actually in your
261// control: confirming is final.
262func ConfirmReceived(cur realm, escrowID int) {
263 mustUserCall(cur)
264 e := getEscrow(escrowID)
265 require(e.Buyer == cur.Previous().Address(), "buyer only")
266 require(core.CanBuyerConfirm(e.State), "cannot confirm in state "+e.State.String())
267 e.State = core.StateCompleted
268 settle(cur, e)
269 chain.Emit("EscrowCompleted", "id", strconv.Itoa(escrowID))
270}
271
272// ClaimTimeoutRefund returns the full locked amount to the buyer after
273// RefundWindow has passed without the seller submitting a transfer.
274func ClaimTimeoutRefund(cur realm, escrowID int) {
275 mustUserCall(cur)
276 e := getEscrow(escrowID)
277 require(e.Buyer == cur.Previous().Address(), "buyer only")
278 require(core.CanTimeoutRefund(e.State), "no timeout refund in state "+e.State.String())
279 require(time.Since(e.FundedAt) >= RefundWindow, "refund window not reached")
280 e.State = core.StateRefunded
281 send(cur, e.Buyer, e.LockedUgnot)
282 chain.Emit("EscrowRefunded", "id", strconv.Itoa(escrowID), "reason", "timeout")
283}
284
285// OpenDispute freezes a live trade for the arbiter. Either party may open
286// one; the reason is stored on-chain.
287func OpenDispute(cur realm, escrowID int, reason string) {
288 mustUserCall(cur)
289 e := getEscrow(escrowID)
290 party := cur.Previous().Address()
291 require(party == e.Buyer || party == e.Seller, "parties only")
292 require(core.CanDispute(e.State), "cannot dispute in state "+e.State.String())
293 require(reason != "", "give a reason")
294 e.State = core.StateDisputed
295 e.DisputeReason = reason
296 chain.Emit("DisputeOpened",
297 "id", strconv.Itoa(escrowID),
298 "by", party.String(),
299 "reason", reason,
300 )
301}
302
303// ResolveDispute settles a disputed trade by arbiter decision: paySeller
304// true pays the seller as on completion; false refunds the buyer in full.
305// Every resolution is public on the record.
306func ResolveDispute(cur realm, escrowID int, paySeller bool) {
307 mustArbiter(cur)
308 e := getEscrow(escrowID)
309 require(e.State == core.StateDisputed, "not disputed")
310 if paySeller {
311 e.State = core.StateResolvedSeller
312 settle(cur, e)
313 } else {
314 e.State = core.StateResolvedBuyer
315 send(cur, e.Buyer, e.LockedUgnot)
316 }
317 chain.Emit("DisputeResolved",
318 "id", strconv.Itoa(escrowID),
319 "paySeller", strconv.FormatBool(paySeller),
320 "arbiter", cur.Previous().Address().String(),
321 )
322}
323
324// settle pays the seller and books the platform fee. The escrow state must
325// already be terminal when this runs.
326func settle(cur realm, e *Escrow) {
327 payout := core.SellerPayout(e.PriceUgnot)
328 fee := e.LockedUgnot - payout
329 require(fee >= 0, "fee underflow")
330 send(cur, e.Seller, payout)
331 feesUgnot += fee
332}