package cust0dy import ( "crypto/sha256" "encoding/hex" "strconv" "time" "chain" "chain/banker" "chain/runtime/unsafe" core "gno.land/p/g1ejwp09wwnu6psem2sdwrh7l7xcldqm6zz3vu2v/cust0dy_core" ) func bankerNew(cur realm) banker.Banker { return banker.NewBanker(banker.BankerTypeRealmSend, cur) } func require(cond bool, msg string) { if !cond { panic(msg) } } // ---- roles ---- // ClaimAdmin makes the caller the marketplace operator, once. The deployer // calls this right after deployment; afterwards it panics for everyone. // The first admin also becomes the first arbiter. func ClaimAdmin(cur realm) { mustUserCall(cur) if admin != address("") { panic("admin already claimed") } admin = cur.Previous().Address() arbiter = admin chain.Emit("AdminClaimed", "admin", admin.String()) } // SetArbiter changes the dispute referee. Admin only. func SetArbiter(cur realm, a address) { mustAdmin(cur) require(a != address(""), "empty arbiter") arbiter = a chain.Emit("ArbiterChanged", "arbiter", a.String()) } // WithdrawFees sends accrued platform fees to the admin. Admin only. func WithdrawFees(cur realm) { mustAdmin(cur) require(feesUgnot > 0, "no fees to withdraw") amt := feesUgnot feesUgnot = 0 send(cur, admin, amt) chain.Emit("FeesWithdrawn", "amount", strconv.FormatInt(amt, 10)) } // ---- sell side ---- // List creates a sell order for a domain, social handle or Gno handle. // The asset is not verified yet; see VerificationCode and AttestVerified. func List(cur realm, kindStr, value string, priceUgnot int64) int { mustUserCall(cur) kind, err := core.ParseKind(kindStr) if err != nil { panic(err.Error()) } require(core.ValidateAsset(kind, value) == nil, "invalid asset for its kind") require(priceUgnot > 0, "price must be positive") require(priceUgnot <= core.MaxPrice, "price too large") listingSeq++ l := &Listing{ ID: listingSeq, Seller: cur.Previous().Address(), Kind: kind, Value: value, PriceUgnot: priceUgnot, State: core.ListingOpen, Created: time.Now(), } listings.Set(strconv.Itoa(l.ID), l) chain.Emit("ListingCreated", "id", strconv.Itoa(l.ID), "seller", l.Seller.String(), "kind", kind.String(), "value", value, "price", strconv.FormatInt(priceUgnot, 10), ) return l.ID } // VerificationCode is the string the seller must publish off-chain to prove // control of the asset: a DNS TXT record for a domain, a bio/post code for // a social or Gno handle. It binds the listing id and the seller address, // so a code cannot be reused for someone else's listing. func VerificationCode(id int) string { l := getListing(id) sum := sha256.Sum256([]byte("cust0dy:" + l.Seller.String() + ":" + strconv.Itoa(id))) return "c0_" + hex.EncodeToString(sum[:])[:12] } // AttestVerified marks a listing as ownership-verified. Only the arbiter // (or admin) may attest, and only after an off-chain check, for example // with verifier/dns_verify.py. The attestation is public and on the record. func AttestVerified(cur realm, id int) { mustArbiter(cur) l := getListing(id) require(l.State == core.ListingOpen, "listing not open") require(!l.Verified, "already verified") l.Verified = true chain.Emit("ListingVerified", "id", strconv.Itoa(id), "arbiter", cur.Previous().Address().String()) } // CancelListing withdraws an open listing. Seller only, and only while no // live escrow holds it. func CancelListing(cur realm, id int) { mustUserCall(cur) l := getListing(id) require(l.Seller == cur.Previous().Address(), "not your listing") require(l.State == core.ListingOpen, "listing not open") l.State = core.ListingCancelled chain.Emit("ListingCancelled", "id", strconv.Itoa(id)) } // ---- buy side ---- // Buy purchases a listing at full price. The buyer must attach exactly // BuyerTotal(price) ugnot (price + 2.5% buyer fee). The coins lock in this // realm until settlement. Returns the escrow id. func Buy(cur realm, listingID int) int { mustUserCall(cur) l := getListing(listingID) require(l.State == core.ListingOpen, "listing not open") buyer := cur.Previous().Address() require(buyer != l.Seller, "cannot buy your own listing") want := core.BuyerTotal(l.PriceUgnot) sent := unsafe.OriginSend() require(len(sent) == 1 && sent[0].Denom == "ugnot" && sent[0].Amount == want, "attach exactly "+strconv.FormatInt(want, 10)+"ugnot (price + 2.5% buyer fee)") l.State = core.ListingSold escrowSeq++ e := &Escrow{ ID: escrowSeq, ListingID: l.ID, Seller: l.Seller, Buyer: buyer, PriceUgnot: l.PriceUgnot, LockedUgnot: want, State: core.StateFunded, FundedAt: time.Now(), } escrows.Set(strconv.Itoa(e.ID), e) chain.Emit("EscrowFunded", "id", strconv.Itoa(e.ID), "listing", strconv.Itoa(l.ID), "buyer", buyer.String(), "locked", strconv.FormatInt(want, 10), ) return e.ID } // MakeOffer locks coins as a buy-side offer on a listing. Offers are // all-in: no extra buyer fee is charged if the seller accepts. Attach the // offered amount as ugnot. Returns the offer id. func MakeOffer(cur realm, listingID int) int { mustUserCall(cur) l := getListing(listingID) require(l.State == core.ListingOpen, "listing not open") maker := cur.Previous().Address() require(maker != l.Seller, "cannot offer on your own listing") sent := unsafe.OriginSend() require(len(sent) == 1 && sent[0].Denom == "ugnot" && sent[0].Amount > 0, "attach the offered amount in ugnot") offerSeq++ o := &Offer{ ID: offerSeq, ListingID: l.ID, Maker: maker, AmountUgnot: sent[0].Amount, Open: true, Created: time.Now(), } offers.Set(strconv.Itoa(o.ID), o) chain.Emit("OfferMade", "id", strconv.Itoa(o.ID), "listing", strconv.Itoa(l.ID), "maker", maker.String(), "amount", strconv.FormatInt(o.AmountUgnot, 10), ) return o.ID } // CancelOffer withdraws an open offer and refunds the maker in full. func CancelOffer(cur realm, offerID int) { mustUserCall(cur) o := getOffer(offerID) require(o.Open, "offer not open") require(o.Maker == cur.Previous().Address(), "not your offer") o.Open = false send(cur, o.Maker, o.AmountUgnot) chain.Emit("OfferCancelled", "id", strconv.Itoa(offerID)) } // AcceptOffer lets the seller accept an open offer. The offer's locked // coins become the escrow; the buyer fee is waived (offers are all-in) and // only the 5% seller fee applies at settlement. Returns the escrow id. func AcceptOffer(cur realm, offerID int) int { mustUserCall(cur) o := getOffer(offerID) require(o.Open, "offer not open") l := getListing(o.ListingID) require(l.Seller == cur.Previous().Address(), "not your listing") require(l.State == core.ListingOpen, "listing not open") o.Open = false l.State = core.ListingSold escrowSeq++ e := &Escrow{ ID: escrowSeq, ListingID: l.ID, Seller: l.Seller, Buyer: o.Maker, PriceUgnot: o.AmountUgnot, LockedUgnot: o.AmountUgnot, State: core.StateFunded, FundedAt: time.Now(), } escrows.Set(strconv.Itoa(e.ID), e) chain.Emit("OfferAccepted", "offer", strconv.Itoa(o.ID), "escrow", strconv.Itoa(e.ID), "listing", strconv.Itoa(l.ID), ) return e.ID } // ---- escrow transitions ---- // MarkTransferSubmitted records that the seller has started the off-chain // handover (registrar push, credential handover, ...). This stops the // buyer's automatic refund window; from here the exits are buyer // confirmation or a dispute. func MarkTransferSubmitted(cur realm, escrowID int) { mustUserCall(cur) e := getEscrow(escrowID) require(e.Seller == cur.Previous().Address(), "seller only") require(e.State == core.StateFunded, "not in funded state") e.State = core.StateTransferSubmitted chain.Emit("TransferSubmitted", "id", strconv.Itoa(escrowID)) } // ConfirmReceived settles the trade: the seller is paid the agreed price // minus the 5% seller fee; the remainder of the locked coins is platform // fee. Buyer only. Never confirm before the asset is actually in your // control: confirming is final. func ConfirmReceived(cur realm, escrowID int) { mustUserCall(cur) e := getEscrow(escrowID) require(e.Buyer == cur.Previous().Address(), "buyer only") require(core.CanBuyerConfirm(e.State), "cannot confirm in state "+e.State.String()) e.State = core.StateCompleted settle(cur, e) chain.Emit("EscrowCompleted", "id", strconv.Itoa(escrowID)) } // ClaimTimeoutRefund returns the full locked amount to the buyer after // RefundWindow has passed without the seller submitting a transfer. func ClaimTimeoutRefund(cur realm, escrowID int) { mustUserCall(cur) e := getEscrow(escrowID) require(e.Buyer == cur.Previous().Address(), "buyer only") require(core.CanTimeoutRefund(e.State), "no timeout refund in state "+e.State.String()) require(time.Since(e.FundedAt) >= RefundWindow, "refund window not reached") e.State = core.StateRefunded send(cur, e.Buyer, e.LockedUgnot) chain.Emit("EscrowRefunded", "id", strconv.Itoa(escrowID), "reason", "timeout") } // OpenDispute freezes a live trade for the arbiter. Either party may open // one; the reason is stored on-chain. func OpenDispute(cur realm, escrowID int, reason string) { mustUserCall(cur) e := getEscrow(escrowID) party := cur.Previous().Address() require(party == e.Buyer || party == e.Seller, "parties only") require(core.CanDispute(e.State), "cannot dispute in state "+e.State.String()) require(reason != "", "give a reason") e.State = core.StateDisputed e.DisputeReason = reason chain.Emit("DisputeOpened", "id", strconv.Itoa(escrowID), "by", party.String(), "reason", reason, ) } // ResolveDispute settles a disputed trade by arbiter decision: paySeller // true pays the seller as on completion; false refunds the buyer in full. // Every resolution is public on the record. func ResolveDispute(cur realm, escrowID int, paySeller bool) { mustArbiter(cur) e := getEscrow(escrowID) require(e.State == core.StateDisputed, "not disputed") if paySeller { e.State = core.StateResolvedSeller settle(cur, e) } else { e.State = core.StateResolvedBuyer send(cur, e.Buyer, e.LockedUgnot) } chain.Emit("DisputeResolved", "id", strconv.Itoa(escrowID), "paySeller", strconv.FormatBool(paySeller), "arbiter", cur.Previous().Address().String(), ) } // settle pays the seller and books the platform fee. The escrow state must // already be terminal when this runs. func settle(cur realm, e *Escrow) { payout := core.SellerPayout(e.PriceUgnot) fee := e.LockedUgnot - payout require(fee >= 0, "fee underflow") send(cur, e.Seller, payout) feesUgnot += fee }