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.

mint.gno

14.20 Kb · 434 lines
  1// Package mint is the platform's first minter (design §2.5.3): sale
  2// phases, fixed price or Dutch auction, live and merkle allowlists, lifetime
  3// wallet caps, and payment settlement. It is replaceable: core binds each
  4// collection to the minter that created it, so a future mint/v2 serves new
  5// collections without touching sales in progress.
  6//
  7// Creator flow (one multi-message transaction from the frontend; safety does
  8// not depend on atomicity because nobody can mint a Draft):
  9//
 10//	Create -> AddPhase x1..3 -> Launch
 11//
 12// Collector flow: Mint, with Price / Phases / Eligible as the read side.
 13package mint
 14
 15import (
 16	"chain"
 17	"chain/runtime"
 18	"strconv"
 19
 20	"gno.land/p/nt/avl/v0"
 21	"gno.land/p/nt/ufmt/v0"
 22
 23	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/safe/v2"
 24	"gno.land/p/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/types/v2"
 25	"gno.land/r/g1jz6j9hj6rdf5ltl2kcrpa4jwtdh3w30z0yul06/sinopia4/core"
 26)
 27
 28const MaxPhases = 3
 29
 30// sale is this minter's per-collection state. Phases can change only while
 31// core says Draft; after Launch they are frozen with the rest (I-6).
 32type sale struct {
 33	phases []types.Phase
 34}
 35
 36var sales avl.Tree // cid -> *sale
 37
 38// Create opens a Draft collection for the calling wallet and pays the
 39// protocol's create fee from the attached ugnot (excess refunded).
 40// Empty payee strings default to "creator:10000". expectedCID, when set,
 41// makes the transaction fail instead of creating a different id than the
 42// frontend showed (OA B2).
 43func Create(cur realm, name, symbol, description, engineID, params string,
 44	maxSupply, royaltyBps int64, primaryPayees, royaltyPayees, expectedCID string,
 45) string {
 46	return createWith(cur, name, symbol, description, engineID, params, maxSupply, royaltyBps,
 47		primaryPayees, royaltyPayees, expectedCID, false)
 48}
 49
 50// CreateSoulbound is Create for a non-transferable collection (badges,
 51// attendance, membership): its tokens never move or get approved, the
 52// market never lists them, the owner may burn one after Final (core I-20).
 53// There are no secondary sales, so royaltyBps must be 0; royaltyPayees
 54// still receives anything sent to the collection's royalty address.
 55func CreateSoulbound(cur realm, name, symbol, description, engineID, params string,
 56	maxSupply, royaltyBps int64, primaryPayees, royaltyPayees, expectedCID string,
 57) string {
 58	return createWith(cur, name, symbol, description, engineID, params, maxSupply, royaltyBps,
 59		primaryPayees, royaltyPayees, expectedCID, true)
 60}
 61
 62func createWith(cur realm, name, symbol, description, engineID, params string,
 63	maxSupply, royaltyBps int64, primaryPayees, royaltyPayees, expectedCID string, soulbound bool,
 64) string {
 65	paid := received(cur)
 66	creator := cur.Previous().Address()
 67	fee := core.FeeConfig()
 68	if paid < fee.CreateFee {
 69		panic("create fee is " + itoa(fee.CreateFee) + "ugnot, sent " + itoa(paid))
 70	}
 71	self := creator.String() + ":10000"
 72	if primaryPayees == "" {
 73		primaryPayees = self
 74	}
 75	if royaltyPayees == "" {
 76		royaltyPayees = self
 77	}
 78
 79	cid := core.CreateCollection(cross(cur), creator, types.CollectionSpec{
 80		Name: name, Symbol: symbol, Description: description,
 81		EngineID: engineID, Params: params,
 82		MaxSupply: maxSupply, RoyaltyBps: royaltyBps,
 83		PrimaryPayees: primaryPayees, RoyaltyPayees: royaltyPayees,
 84		Soulbound: soulbound,
 85	})
 86	if expectedCID != "" && cid != expectedCID {
 87		panic("collection id would be " + cid + ", expected " + expectedCID + "; retry")
 88	}
 89	sales.Set(cid, &sale{})
 90
 91	pay(cur, fee.Treasury, fee.CreateFee)
 92	pay(cur, creator, paid-fee.CreateFee)
 93	return cid
 94}
 95
 96// AddPhase appends a sale phase. Phases are ordered and do not overlap.
 97// kind is "allow" (set required) or "public" (set empty); a fixed price has
 98// startPrice == floorPrice and zero steps; walletCap 0 means no cap.
 99func AddPhase(cur realm, cid, kind, set string,
100	startHeight, endHeight, startPrice, floorPrice, stepBlocks, stepAmount, walletCap int64,
101) {
102	assertNoDeposit(cur)
103	cid = bare(cid)
104	s := mustDraftSale(cur, cid)
105	if len(s.phases) >= MaxPhases {
106		panic("at most " + itoa(MaxPhases) + " phases")
107	}
108	p := types.Phase{
109		Kind: kind, Set: set,
110		StartHeight: startHeight, EndHeight: endHeight,
111		StartPrice: startPrice, FloorPrice: floorPrice,
112		StepBlocks: stepBlocks, StepAmount: stepAmount,
113		WalletCap: walletCap,
114	}
115	if err := p.Validate(); err != nil {
116		panic(err)
117	}
118	if set != "" {
119		parseSet(set)
120	}
121	if n := len(s.phases); n > 0 && p.StartHeight <= s.phases[n-1].EndHeight {
122		panic("phases must not overlap: start after height " + itoa(s.phases[n-1].EndHeight))
123	}
124	s.phases = append(s.phases, p)
125	chain.Emit("PhaseAdded", "cid", cid, "index", itoa(int64(len(s.phases)-1)), "kind", kind, "set", set)
126}
127
128// ClearPhases removes every phase of a Draft.
129func ClearPhases(cur realm, cid string) {
130	assertNoDeposit(cur)
131	cid = bare(cid)
132	s := mustDraftSale(cur, cid)
133	s.phases = nil
134	chain.Emit("PhasesCleared", "cid", cid)
135}
136
137// Launch freezes the sale. mode is types.ModeReveal ("") or
138// types.ModeOpen ("open"); core judges every combination and this minter
139// adds no rule of its own.
140//
141// Reveal mode: creatorCommit is safe.Commit(chainID, cid, "creator",
142// secret), computed off-chain — never send the secret to a node before
143// reveal. beaconSource (with useBeacon) is "" / "committed" for the
144// platform beacon or an approved randomness provider's package path
145// (core.RandomnessProviders).
146// Open mode (badges, editions, event drops): no secret, no beacon, no
147// reserve and no reveal window — creatorCommit "", revealWindow 0,
148// useBeacon false, beaconSource ""; the seed is public from the start and
149// the collection is never a fair launch (core I-17).
150// The engine-author fee is snapshotted here; the engine's launch gate
151// (CheckLaunch) runs inside core.Launch.
152func Launch(cur realm, cid, creatorCommit string, revealWindow int64, useBeacon bool, beaconSource, mode string) {
153	assertNoDeposit(cur)
154	cid = bare(cid)
155	s := mustDraftSale(cur, cid)
156	if len(s.phases) == 0 {
157		panic("add at least one phase before launching")
158	}
159	core.Launch(cross(cur), cid, types.LaunchSpec{
160		StartHeight:   s.phases[0].StartHeight,
161		EndHeight:     s.phases[len(s.phases)-1].EndHeight,
162		RevealWindow:  revealWindow,
163		CreatorCommit: creatorCommit,
164		UseBeacon:     useBeacon,
165		BeaconSource:  beaconSource,
166		Mode:          mode,
167	})
168}
169
170// Abort returns a launched collection with no mints to Draft (core rules).
171func Abort(cur realm, cid string) {
172	assertNoDeposit(cur)
173	cid = bare(cid)
174	assertCreator(cur, cid)
175	core.AbortLaunch(cross(cur), cid)
176}
177
178// Reserve mints the creator's reserve to the creator before the sale.
179func Reserve(cur realm, cid string, count int64) string {
180	assertNoDeposit(cur)
181	cid = bare(cid)
182	creator := assertCreator(cur, cid)
183	first, last := core.ReserveTo(cross(cur), cid, creator, count)
184	return itoa(first) + "-" + itoa(last)
185}
186
187// Mint buys count tokens in the phase open at this block, at that block's
188// unit price, never above maxUnitPrice (a Dutch step cannot surprise the
189// buyer). proof is the merkle proof for merkle sets, otherwise "". Returns
190// "first-last". Every attached unit is paid out or refunded (I-3, I-4).
191func Mint(cur realm, cid string, count, maxUnitPrice int64, proof string) string {
192	paid := received(cur)
193	cid = bare(cid)
194	buyer := cur.Previous().Address()
195	h := runtime.ChainHeight()
196	p, ok := mustSale(cid).phaseAt(h)
197	if !ok {
198		panic("no sale phase is open at height " + itoa(h))
199	}
200	if count <= 0 || count > core.MaxMintPerTx {
201		panic("count must be 1.." + itoa(core.MaxMintPerTx))
202	}
203	if ok, reason := eligible(cid, p.Set, buyer, proof); !ok {
204		panic(reason)
205	}
206	if p.WalletCap > 0 && core.MintedBy(cid, buyer)+count > p.WalletCap {
207		panic("wallet cap: " + itoa(p.WalletCap) + " per wallet, already minted " + itoa(core.MintedBy(cid, buyer)))
208	}
209	price := p.PriceAt(h)
210	if price > maxUnitPrice {
211		panic("unit price at this block is " + itoa(price) + "ugnot, above maxUnitPrice " + itoa(maxUnitPrice))
212	}
213	cost := price * count
214	if paid < cost {
215		panic("send " + itoa(cost) + "ugnot, sent " + itoa(paid))
216	}
217
218	first, last := core.MintTo(cross(cur), cid, buyer, count)
219
220	fee := core.FeeConfig()
221	sp := split(cid, cost)
222	pay(cur, fee.Treasury, sp.protocol)
223	pay(cur, sp.engineAuthor, sp.engine)
224	for i, payee := range sp.payees {
225		pay(cur, payee.Addr, sp.shares[i])
226	}
227	pay(cur, buyer, paid-cost)
228
229	chain.Emit("Sale", "cid", cid, "buyer", buyer.String(), "first", itoa(first), "last", itoa(last),
230		"unitPrice", itoa(price), "protocolFee", itoa(sp.protocol), "engineFee", itoa(sp.engine),
231		"engineAuthor", sp.engineAuthor.String())
232	return itoa(first) + "-" + itoa(last)
233}
234
235// primarySplit is how a primary sale of `amount` is paid (I-4: protocol +
236// engine + sum(shares) == amount): the protocol fee frozen at Launch
237// (SA-I5), the engine author's fee (snapshot at Launch, 0 when the creator
238// is the author), the rest split over the frozen primary payees.
239type primarySplit struct {
240	protocol, engine int64
241	engineAuthor     address
242	payees           []types.Payee
243	shares           []int64
244}
245
246func split(cid string, amount int64) primarySplit {
247	sp := primarySplit{protocol: safe.BpsOf(amount, core.PrimaryFeeBps(cid))}
248	author, bps := core.EngineFee(cid)
249	sp.engineAuthor, sp.engine = author, safe.BpsOf(amount, bps)
250	sp.payees = core.PrimaryPayees(cid)
251	sp.shares = safe.SplitByBps(amount-sp.protocol-sp.engine, sp.payees)
252	return sp
253}
254
255func (s *sale) phaseAt(h int64) (types.Phase, bool) {
256	for _, p := range s.phases {
257		if p.Covers(h) {
258			return p, true
259		}
260	}
261	return types.Phase{}, false
262}
263
264// mustSale takes the bare id (callers apply bare once, at the entry point).
265func mustSale(cid string) *sale {
266	v := sales.Get(cid)
267	if v == nil {
268		panic("collection " + cid + " was not created by this minter")
269	}
270	return v.(*sale)
271}
272
273func mustDraftSale(cur realm, cid string) *sale {
274	assertCreator(cur, cid)
275	if core.Info(cid).State != types.StateDraft {
276		panic("phases are frozen after launch")
277	}
278	return mustSale(cid)
279}
280
281func assertCreator(cur realm, cid string) address {
282	who := cur.Previous().Address()
283	if core.Info(cid).Creator != who {
284		panic("only the collection's creator can do this")
285	}
286	return who
287}
288
289// --- reads -------------------------------------------------------------------
290
291// Price is the unit price at height h, or -1 when no phase covers h.
292func Price(cid string, h int64) int64 {
293	cid = bare(cid)
294	p, ok := mustSale(cid).phaseAt(h)
295	if !ok {
296		return -1
297	}
298	return p.PriceAt(h)
299}
300
301// Phases is the phase list as JSON.
302func Phases(cid string) string {
303	cid = bare(cid)
304	w := &safe.JSONWriter{}
305	w.BeginArray()
306	for _, p := range mustSale(cid).phases {
307		w.BeginObject()
308		w.StrField("kind", p.Kind)
309		w.StrField("set", p.Set)
310		w.IntField("startHeight", p.StartHeight)
311		w.IntField("endHeight", p.EndHeight)
312		w.IntField("startPrice", p.StartPrice)
313		w.IntField("floorPrice", p.FloorPrice)
314		w.IntField("stepBlocks", p.StepBlocks)
315		w.IntField("stepAmount", p.StepAmount)
316		w.IntField("walletCap", p.WalletCap)
317		w.EndObject()
318	}
319	w.EndArray()
320	return w.String()
321}
322
323// Eligible answers "can addr mint now, and how many?" with the same checks
324// Mint runs, so the UI never disagrees with the chain (OA B3). JSON:
325// {phase, kind, eligible, reason, remainingCap (-1 = no cap), price}.
326func Eligible(cid string, addr address, proof string) string {
327	cid = bare(cid)
328	h := runtime.ChainHeight()
329	w := &safe.JSONWriter{}
330	w.BeginObject()
331	idx, p := -1, types.Phase{}
332	for i, q := range mustSale(cid).phases {
333		if q.Covers(h) {
334			idx, p = i, q
335			break
336		}
337	}
338	w.IntField("phase", int64(idx))
339	if idx < 0 {
340		w.BoolField("eligible", false)
341		w.StrField("reason", "no sale phase is open at height "+itoa(h))
342		w.EndObject()
343		return w.String()
344	}
345	ok, reason := eligible(cid, p.Set, addr, proof)
346	remaining := int64(-1)
347	if p.WalletCap > 0 {
348		minted := core.MintedBy(cid, addr) // -1 once Final: nothing left to mint anyway
349		if minted < 0 {
350			minted = p.WalletCap
351		}
352		remaining = p.WalletCap - minted
353		if remaining < 0 {
354			remaining = 0
355		}
356		if remaining == 0 && ok {
357			ok, reason = false, "wallet cap reached"
358		}
359	}
360	if ok && core.Info(cid).State != types.StateMinting {
361		ok, reason = false, "collection is not minting"
362	}
363	w.StrField("kind", p.Kind)
364	w.BoolField("eligible", ok)
365	w.StrField("reason", reason)
366	w.IntField("remainingCap", remaining)
367	w.IntField("price", p.PriceAt(h))
368	w.EndObject()
369	return w.String()
370}
371
372// Quote is what Mint(cid, count, …) pays at height h, as JSON: {count,
373// unitPrice, cost, protocolFee, protocolBps, engineFee, engineBps,
374// engineAuthor, payees:[{address, amount}]}; unitPrice -1 outside phases.
375func Quote(cid string, count, h int64) string {
376	cid = bare(cid)
377	price := Price(cid, h)
378	w := &safe.JSONWriter{}
379	w.BeginObject()
380	w.IntField("count", count)
381	w.IntField("unitPrice", price)
382	if price < 0 || count <= 0 || count > core.MaxMintPerTx {
383		w.EndObject()
384		return w.String()
385	}
386	cost := price * count
387	sp := split(cid, cost)
388	_, bps := core.EngineFee(cid)
389	w.IntField("cost", cost)
390	w.IntField("protocolFee", sp.protocol)
391	w.IntField("protocolBps", core.PrimaryFeeBps(cid))
392	w.IntField("engineFee", sp.engine)
393	w.IntField("engineBps", bps)
394	w.StrField("engineAuthor", sp.engineAuthor.String())
395	w.Key("payees")
396	w.BeginArray()
397	for i, p := range sp.payees {
398		w.BeginObject()
399		w.StrField("address", p.Addr.String())
400		w.IntField("amount", sp.shares[i])
401		w.EndObject()
402	}
403	w.EndArray()
404	w.EndObject()
405	return w.String()
406}
407
408func Render(path string) string {
409	if path == "" {
410		return "# mint/v1\n\nSale phases of the platform's collections. Use `:<cid>` for one collection.\n"
411	}
412	path = bare(path)
413	s := mustSale(path) // only known collection ids get this far
414	out := "# Sale of collection " + path + "\n\n"
415	for i, p := range s.phases {
416		out += ufmt.Sprintf("%d. %s phase, heights %d-%d, price %d -> %d ugnot, wallet cap %d\n",
417			i+1, p.Kind, p.StartHeight, p.EndHeight, p.StartPrice, p.FloorPrice, p.WalletCap)
418	}
419	return out
420}
421
422func itoa(n int64) string { return strconv.FormatInt(n, 10) }
423
424// bare is the collection id without core's token sub-path prefix: core
425// accepts "<cid>" and "c/<cid>" (K-1, the key wallets derive from
426// Token.ID()), this minter keys its sales, merkle leaves and events by the
427// bare id only, so one collection has one spelling here too. Anything
428// else ("c/c/1", "01") is left as is and refused by core or by mustSale.
429func bare(cid string) string {
430	if len(cid) > 2 && cid[0] == 'c' && cid[1] == '/' {
431		return cid[2:]
432	}
433	return cid
434}